Apple的Developer Reference提到如果没有强引用对象,则会释放该对象。如果从弱引用调用的实例方法正在执行中,会发生这种情况吗?
例如,请考虑以下代码段 -
@interface ExampleObject
- doSomething;
@end
@interface StrongCaller
@property ExampleObject *strong;
@end
@implementation StrongCaller
- initWithExampleInstance:(ExampleObject *) example
{
_strong = example;
}
- doSomething
{
....
[strong doSomething];
....
strong = nil;
....
}
@end
@interface WeakCaller
@property (weak) ExampleObject *weak;
@end
@implementation WeakCaller
- initWithExampleInstance:(ExampleObject *) example
{
_weak = example;
}
- doSomething
{
....
[weak doSomething];
....
}
@end
现在,在主线程中,
ExampleObject *object = [[ExampleObject alloc] init];
在主题1中,
[[StrongCaller initWithExampleInstance:object] doSomething];
在Thread2中,
[[WeakCaller initWithExampleInstance:object] doSomething];
假设主线程不再持有对象的引用,当执行[weak doSomething]时,如果strong设置为nil会发生什么?在这种情况下,对象是GC吗?
答案 0 :(得分:1)
通常这个问题发生在异步块执行期间,通过更改逻辑无法避免此问题。
但如果您确定不想更改逻辑,则可以在您的情况下使用相同的解决方案。你应该这样修改你的方法
- (void) doSomething
{
Your_Class *pointer = self; //Now this local variable keeps strong reference to self
if(pointer != nil){ // self is not deallocated
... your code here
}
//Here pointer will be deleted and strong reference will be released automatically
}