有没有办法对原子属性进行延迟初始化而无需手动编写setter和getter?

ope*_*rog 3 iphone objective-c ipad ios xcode4

显然,在覆盖原子属性访问器时不可能使用@synthesize.Xcode 4会产生警告.

现在,有没有另一种使用原子属性延迟初始化方法,同时仍让Xcode自动合成getter和setter,而不会覆盖其中的任何一个?

hyp*_*ypt 6

你需要做的是同时写下setter和getter.你仍然@synthesize可以获得存储空间.例如:

//.h
@property (strong) id x;

//.m

@synthesize x = _x;
- (id)x
{
    @synchronized(self)
    {
        if (!_x)
        {
            _x = [[MyX alloc] init];
        }
        return _x;
    }
}

- (void)setX:(id)x
{
    @synchronized(self)
    {
        _x = x;
    }
}
Run Code Online (Sandbox Code Playgroud)

您可能需要在没有ARC的情况下进行额外的内存管理,并且可能需要创建不同的锁(而不是self)或使用不同的同步方法,但它会为您提供要点.