Reputation: 23
Apple's Developer Reference mentions that a an object is deallocated if there are no strong reference to it. Can this happen if an instance method called from a weak reference is in the middle of execution?
For example, consider the below snippet -
@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
Now, In main thread,
ExampleObject *object = [[ExampleObject alloc] init];
In Thread 1,
[[StrongCaller initWithExampleInstance:object] doSomething];
In Thread2,
[[WeakCaller initWithExampleInstance:object] doSomething];
Assuming that the main thread no longer holds a reference to object, what would happen if strong is set to nil, when [weak doSomething] is executing? Is the object GC'ed in this case?
Upvotes: 2
Views: 913
Reputation: 17043
Normally this problem happens during asynchronously blocks execution where there is impossible to avoid this problem by changing logic.
But if you are sure that you do not want to change logic you can use the same solution in your case. You should modify your method this way
- (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
}
Upvotes: 1