【发布时间】:2020-06-19 18:08:19
【问题描述】:
我的班级中有一个自定义对象属性。我在一个函数中分配这个对象。一旦函数执行完毕,该属性就会被释放。我不希望这种情况发生。我希望该对象一直存在,直到对 MyClass 的引用处于活动状态。
这是与ARC。
这是代码
@interface MyClass : NSObject
@property (nonatomic, strong) MyCustomClass *obj;
@end
@implementation MyClass
- (id)init {
// initialize
_obj = nil;
}
- (void)func {
_obj = [[MyCustomClass alloc] initWithParams...];
// do more things
}
// the object deallocates once the function exits.
【问题讨论】:
-
你说“这是 ARC”,但我不得不否认这一点。使用 ARC,分配给
_obj也保留,除非您替换它,否则 MyCustomClass 对象不会被释放,或者除非 MyClass 本身被释放。我建议你实现dealloc看看是不是这样。要么是,要么你没有像你认为的那样在 ARC 下运行。 -
顺便说一句,在初始化程序中没有理由说
_obj = nil。已经是nil。 -
在唯一提供的代码中,
_obj将使用或不使用 ARC 独立存储MyCustomClass的新实例。如果它在函数退出时被释放,则意味着 ARC 已打开(否则它会泄漏或持续存在),并且!,do more things 中的某些内容要么替换_obj实例,要么将其设置为nil.
标签: objective-c properties automatic-ref-counting