Re: Debugging memory leak in NSURLSession with ARC
Re: Debugging memory leak in NSURLSession with ARC
- Subject: Re: Debugging memory leak in NSURLSession with ARC
- From: Roland King <email@hidden>
- Date: Fri, 02 Jan 2015 10:46:54 +0800
>
> My handler block refers to 'self' quite extensively - it calls other methods of self and also refers to properties such as self.delegate. I'm not quite sure how I can rework it not to refer to self. Maybe I just need to not use the completion block approach and use a delegate callback instead. I need to go away and think about this... thanks for the slap about the head.
>
> --Graham
>
>
Having a handler block which refers to self is not in and of itself a problem, very many blocks implicitly do. The block retains self, however in most cases something else retains the block and the self reference goes away when the block is released. The problem usually comes when the handler block which refers to self is also a property of the object, eg myObj.completion = ^{ .. block referring to myobj }. Xcode normally warns you if you even get close to doing that however.
If that's happening then allocations should show you are amassing whatever objects those are and never releasing them, does it? Or you can be old skool about it and NSLog() dealloc() to see if it's getting called.
Two ways around block retain cycles are
1) If the block is a property of the object, eg a callback block, when you've called the block, nil the property, break the cycle.
2) The strong/weak dance. You make a weak pointer to self which is actually captured in the block, then in the block you assign it to a strong pointer, then check for nil, then use that pointer.
MyObj __weak *weakSelf = self;
^{
MyObj *strongSelf = weakSelf;
if( strongSelf )
{
// do work using strongSelf explicitly
}
}
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden