Apple的开发人员参考指出,如果没有强引用,则释放对象。如果从弱引用调用的实例方法处于执行过程中,会发生这种情况吗?iOS - 执行期间的对象释放
例如,请考虑下面的代码片段 -
@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];
假设主线程不再持有对象的引用,如果强[strong doSomething]正在执行时设置为nil,会发生什么情况?在这种情况下对象GC'ed?
是的,它可以发生在对象的方法调用的中间。潜在的症状是相当不可预测的。 –
好的。这怎么可以避免?此外,这不会使一个弱引用不适合并发编程吗? –
可以通过在某处保留强有力的参考来避免。 –