0

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

这可能吗?

例如:

@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
4

2 回答 2

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;
}

因此,当您设置 public 时lazyObject,请取消您的 private :

- (void)setLazyObject:(id)lazyObject {
    self->_lazyObject = lazyObject; // Weak ownership
    self.privateLazyObject = nil; // Release any existing strong one.
}
于 2013-10-03T11:24:30.687 回答
0

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

于 2013-10-03T11:08:53.217 回答