Skip to content

Instantly share code, notes, and snippets.

@juliengrimault
Created May 14, 2012 08:48
Show Gist options
  • Save juliengrimault/2692793 to your computer and use it in GitHub Desktop.
Save juliengrimault/2692793 to your computer and use it in GitHub Desktop.
Retain cycle in MKNetworkOperation completion handler
@interface Engine
+ (id)sharedEngine;
- (MKNetworkOperation*)someOperation:(CompletionBlock)block onError:(ErrorBlock)errorBlock;
@end
@interface MyViewController : UITableViewController
@property (nonatomic, strong) MKNetworkOperation* operation;
@end
@implementation MyViewController
@synthesize operation = operation;
- (void)setOperation:(MKNetworkOperation*)operation
{
if (_operation == operation) return;
[_operation cancel];
_operation = operation;
}
- (void)viewDidAppear:(BOOL)animated
{
self.operation = [[Engine sharedEngine] someOperation:^(NSArray* images)
{
self.flickrImages = images;
[self.tableView reloadData];//retain cycle here
}
onError:^(NSError* error) {
}];
}
@end
My VC has a strong reference to the operation that in turn copies the completion block that retains `self`, this creates a retain cycle I believe.
A way to break it would be set the operation to nil in `viewDidDisapear:`
- (void)viewDidDisappear:(BOOL)animated
{
self.operation = nil;
}
or to create a weak reference of self
- (void)viewDidAppear:(BOOL)animated
{
__weak MyViewController* weakSelf = self;
self.operation = [[Engine sharedEngine] someOperation:^(NSArray* images)
{
weakSelf.flickrImages = images;
[weakSelf.tableView reloadData];
}
onError:^(NSError* error) {
}];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment