iOS - 执行期间的对象释放



Apple的开发人员参考提到,如果没有对对象的强引用,则会释放该对象。如果从弱引用调用的实例方法正在执行过程中,会发生这种情况吗?

例如,考虑以下代码段 -

@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];

在线程 2 中,

[[WeakCaller initWithExampleInstance:object] doSomething];

假设主线程不再包含对对象的引用,当 [weak doSomething] 正在执行时,如果将 strong 设置为 nil 会发生什么?在这种情况下,对象是否为 GC?

通常,此问题发生在异步块执行期间,无法通过更改逻辑来避免此问题。

但是,如果您确定不想更改逻辑,则可以在自己的情况下使用相同的解决方案。您应该以这种方式修改方法

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

最新更新