iOS Blocks Async Callbacks Causing Crash after View Controller is deallocated

和自甴很熟 提交于 2019-12-11 02:55:30

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!