2

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

这种情况似乎类似于在 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);
    }];
}
4

1 回答 1

0

您可以使用通知中心来侦听视图何时被释放并将块设置为 nil,这样它就不会尝试返回任何内容..

在视图被释放之前发布通知:

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

并注册一个活动:

[[NSNotificationCenter defaultCenter]
 addObserver:listenerObject
 selector:@selector(receivingMethodOnListener:)
 name:@"myNotificationName"
 object:nil];
于 2014-01-10T12:34:49.153 回答