延迟加载弱实例变量

时间:2013-10-03 10:58:10

标签: ios objective-c automatic-ref-counting lazy-loading

我想延迟加载一个实例变量 - 但如果它是从类外部设置的,我不想强​​烈指向它。

这可能吗?

例如:

@interface MyClass

@property (nonatomic,weak) LazyLoadedObject lazyObject;
@end

@implemetation MyClass

-(LazyLoadedObject *)lazyObject
{
  if (_lazyObject== nil)
  {
    //create a object and strongly point to it
    _lazyObject = [LazyLoadedObject new]
  }
  return _lazyObject;
}
@end

2 个答案:

答案 0 :(得分:1)

如果需要,为您的私人网站创建另一个属性,您将拥有强大的参考资料。

@property (nonatomic, weak) id lazyObject;
@property (nonatomic, strong) id privateLazyObject;

然后实现这样的getter:

- (id)lazyObject {
    // If contains value, return that, otherwise redirect to private strong value.
    return self->_lazyObject ?: self.privateLazyObject;
}

- (id)privateLazyObject {
    // Standard lazy getter
    if ( ! self->_privateLazyObject) {
        self.privateLazyObject = ...; // Strong ownership
    }
    return self->_privateLazyObject;
}

因此,当您设置公开lazyObject时,请将您的私人资格取消:

- (void)setLazyObject:(id)lazyObject {
    self->_lazyObject = lazyObject; // Weak ownership
    self.privateLazyObject = nil; // Release any existing strong one.
}

答案 1 :(得分:0)

制作属性strong,因为您想“强烈指向它”。