iOS阻止异步回调在视图控制器被释放后导致崩溃

时间:2012-11-29 07:44:33

标签: ios crash block

我有一个单例类,其中一个方法将成功和失败块作为参数,它调用另一个异步执行的方法,并使用成功和失败块。我的方法的成功块由异步方法的成功块调用。除非我的视图控制器在成功块返回之前被取消分配,否则一切都很有效,在这种情况下应用程序崩溃。

这种情况似乎类似于在dealloc方法中将委托设置为nil。我应该如何处理块?

以下是我的代码:

- (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 个答案:

答案 0 :(得分:0)

您可以使用通知中心在视图被取消分配时进行侦听,并将块设置为nil,这样它就不会尝试返回任何内容。

在取消分配视图之前发布通知:

[[NSNotificationCenter defaultCenter]
 postNotificationName:@"myNotificationName"
 object:broadcasterObject];

并注册活动:

[[NSNotificationCenter defaultCenter]
 addObserver:listenerObject
 selector:@selector(receivingMethodOnListener:)
 name:@"myNotificationName"
 object:nil];