取消分配View Controller后,iOS阻止异步回调导致崩溃 [英] iOS Blocks Async Callbacks Causing Crash after View Controller is deallocated

查看:56
本文介绍了取消分配View Controller后,iOS阻止异步回调导致崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个单例类,该类具有以成功和失败块为参数的方法,它调用另一个方法,该方法异步执行,并且也使用成功和失败块.我的方法的成功块由异步方法的成功块调用.除非我的视图控制器在成功块返回之前被解除分配,否则一切都会运转良好.在这种情况下,应用程序将崩溃.

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.

这种情况似乎类似于在dealloc方法中将委托设置为nil.我应该如何用积木来解决这个问题?

This situation seems analogous to setting a delegate to nil in the dealloc method. How should I handle this with blocks ?

这是我的代码:

- (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);
    }];
}

推荐答案

您可以使用Notification Center来侦听视图被释放时的情况,并将该块设置为nil,这样它就不会尝试返回任何内容.

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];

并注册活动:

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

这篇关于取消分配View Controller后,iOS阻止异步回调导致崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆