调用dealloc后如何停止运行块? IOS

时间:2014-08-27 09:51:40

标签: ios objective-c objective-c-blocks

我有这段代码:

__block NSMutableArray *subCategoriesBlock = self.subCategories ;
__block UITableView *lstSubCategoriesBlock = self.lstSubCategories;
[[AsyncRequest initRequest: onCompletedBlock:^(NSMutableArray *subcategories) {
        [subCategoriesBlock addObjectsFromArray:subcategories];
        [lstSubCategoriesBlock reloadData];

    }]ExecuteRequest];

AsyncRequest类将在后台发送http请求,然后运行onCompletedBlock。

我的问题: 有时系统会释放当前视图控制器,然后调用onCompleted块,并在[lstSubCategoriesBlock reloadData]上崩溃,因为它已经解除分配。

我应该怎么做,以防止系统在重新发布viewContorller时执行[lstSubCategoriesBlock reloadData]

1 个答案:

答案 0 :(得分:4)

使用__weak以便在取消分配对象时,它指向nil

__block __weak NSMutableArray *subCategoriesBlock = self.subCategories ;
__block __weak UITableView *lstSubCategoriesBlock = self.lstSubCategories;
[[AsyncRequest initRequest: onCompletedBlock:^(NSMutableArray *subcategories) {
        [subCategoriesBlock addObjectsFromArray:subcategories];
        [lstSubCategoriesBlock reloadData];

    }]ExecuteRequest];