一傻唾、使用block會產(chǎn)生內(nèi)存泄漏的情況
1.block作為控制器的屬性,沒有用weakself弱化(self直接持有block)
//self直接持有次block
self.testBlock(self.tag);
2.MJRefreshHeader 下拉刷新的block(self間接持有這個block)
//下拉刷新 或者上拉刷新都需要弱化
self.tableView.mj_header=[MJRefreshNormalHeader headerWithRefreshingBlock:^{
[weakSelf dosomething];
}];
二、不會產(chǎn)生內(nèi)存泄漏的情況
1.常用的block
//當(dāng)前的self沒有直接(或者間接)持有block
1.[UIView animateWithDuration:0.1 animations:^{
self.view.frame=CGRectMake(100, 100, 100, 100);
}];
2.[self.array enumerateObjectsUsingBlock:^(NSString *str, NSUInteger idx, BOOL * _Nonnull stop) {
[self dosomething:str];
}];
3.GCD的block和AFNetworking的block 和上面相同,沒有直接強引用block,不會產(chǎn)生內(nèi)存泄漏
但是黍判,以下情況如果你弱化了
__weak __typeof__(self) weakSelf = self;
//在 doSomething 中,weakSelf 不會變成 nil,不過在 doSomething 執(zhí)行完成后肖爵,調(diào)用第二個方法 doOtherThing 的時候,weakSelf 有可能被釋放臀脏,于是劝堪,strongSelf 就派上用場了:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
__strong __typeof(self) strongSelf = weakSelf;
[strongSelf doSomething]; //這是weak self被釋放,必須用strongSelf
[strongSelf doOtherThing];
});
2.直接使用block
//直接使用block揉稚,沒有作為self的屬性
TestBlock testBlock = ^()
{
NSLog(@"%@",self.view);
};
[self test:testBlock];
3.作為參數(shù)傳遞數(shù)據(jù)的時候
-(void)loadData{
[self loadDataCompletion:^(Minemodel *mineModel){
//刷新數(shù)據(jù)
}];
}
-(void)loadDataCompletion:(void(^)(MineModel*mineModel))block{
// 請求服務(wù)端數(shù)據(jù)
NSString *getMineUrl = [NSString stringWithFormat:@"%@",mineurl];
[HttpTool postWithUrl:getMineUrl params:pramaDic success:^(id json) {
NSDictionary *dict = json;
self.mineModel = [[MineModel alloc] init];
[self.mineModel setValuesForKeysWithDictionary:dict];
block(self.mineModel);
} failure:^(NSError *error) {
NSLog(@"錯誤%@",error.localizedDescription);
}];
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者