问题
I have a singleton class with a method that takes a success and failure block as parameters, it calls another method which executes asynchronously and also uses success and failure blocks. The success block for my method is called by the success block of the asynchronous method. Everything works great unless my view controller gets deallocated before the success block returns in which case the app crashes.
This situation seems analogous to setting a delegate to nil in the dealloc method. How should I handle this with blocks ?
Here's what my code looks like:
- (void)getObjectsWithId:(NSInteger)id success:(void (^)(NSArray *objects))success failure:(void (^)(NSInteger statusCode, NSError *error))failure {
NSString *path = [NSString stringWithFormat:@"/my_objects/%d/objects", id];
[self getPath:path parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSMutableArray *objects = [[NSMutableArray alloc] initWithCapacity:[responseObject count]];
for (NSDictionary *dict in responseObject) {
Object *object = [[Object alloc] initWithDictionary:dict];
[objects addObject:object];
}
success(objects);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
failure(operation.response.statusCode, error);
}];
}
回答1:
You can use Notification center to listen when the view gets deallocated and set the block to nil so it won't try to return anything back..
posting a notification right before the view gets dealloced:
[[NSNotificationCenter defaultCenter]
postNotificationName:@"myNotificationName"
object:broadcasterObject];
and registering for an event:
[[NSNotificationCenter defaultCenter]
addObserver:listenerObject
selector:@selector(receivingMethodOnListener:)
name:@"myNotificationName"
object:nil];
来源:https://stackoverflow.com/questions/13621028/ios-blocks-async-callbacks-causing-crash-after-view-controller-is-deallocated