我有一个懒惰地创建对象并将其存储为弱属性的类。其他类可能会请求这个对象,但显然必须保持对它的强引用以防止对象被释放:
// .h
@interface ObjectManager
@property(nonatomic, weak, readonly) NSObject *theObject;
@end
// .m
@interface ObjectManager ()
@property(nonatomic, weak, readwrite) NSObject *theObject;
@end
@implementation ObjectManager
- (NSObject *)theObject
{
if (!_theObject) {
_theObject = [[NSObject alloc] init];
// Perform further setup of _theObject...
}
return _theObject;
}
@end
当该方案设置为 Xcode 为 Debug 构建时,一切正常 - 一个对象可以调用objectManagerInstance.theObject
并返回theObject
。
当方案设置为发布时,theObject
返回nil
:
// Build for Debug:
NSObject *object = objectManagerInstance.theObject;
// object is now pointing to theObject.
// Build for Release:
NSObject *object = objectManagerInstance.theObject;
// object is now `nil`.
我的猜测是编译器正在优化我的代码,因为_theObject
它没有在访问器方法本身中进一步使用,因此nil
在返回之前将弱变量设置为。看来我必须在实际返回变量之前创建一个强引用,我只能认为使用块来做,但会很乱,我宁愿避免它!
是否有某种关键字可以与返回类型一起使用来阻止 ivar 这么快被取消?