Is it ok to access a delegate property from an Block?
@interface TheObject : NSObject
...
@property (nonatomic, assign) id<SomeDelegate> delegate;
@synthesize delegate
- (void) someMethod {
[someObject doSomethingWithCompletionHandler:^(NSArray *)someArray {
[self.delegate otherMethod:someArray];
}];
}
What happens if the delegate is nilled (from the dealloc method in the object that has also set the delegate) before the completion handler is called?
Could it be a memory bug?
I don’t know how to use __block for properties…
Answer from below:
If the delegate is nilled from the object which is the delegate on the dealloc call, everything is fine.
@property (nonatomic, retain) TheObject theObject;
@synthezise theObject = _theObject;
- (void) thatMethod {
self.theObject = [[TheObject alloc] init] autorelease];
_theObject.delegate = self;
}
- (void) dealloc {
_theObject.delegate = nil;
self.theObject = nil;
}
Normally, if your
delegateis deallocated before the block is executed, then it would access garbage, since the block is anassignproperty and the block retainsselfrather than thedelegatesince you access it by reference.However, since you’ve set it up so that
self.delegategets nilled ifdelegateis deallocated, you won’t have that problem. Instead, if yourdelegatewere deallocated, then in your code you’d just be sending theotherMethod:method tonil, which would do nothing, but also cause no errors.If you want the method to definitely be sent to your
delegate, the solution is to access it by value instead of reference:That way
delegateForBlockwill be a pointer to the same object asself.delegate(at the time you executesomeMethod:), and it will be retained.To find out more about how this works, check out Blocks Programming Topics.