iOS 不走dealloc的其中一个原因(个人感觉很重要)

最近地图界面C上出现了偶发性的崩溃,A push B, B push C, C pop B,C走dealloc,然后B pop A的时候,B没走dealloc方法,研究发现,锁定到出问题的是哪一行了,直接上代码。

static NSString *AS_ZBPublishTwoCellID = @"AS_ZBPublishTwoCell";
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    AS_ZBPublishTwoCell *twoCell = [tableView cellForRowAtIndexPath:indexPath]; //根据indexPath准确地取出一行,而不是从cell重用队列中取出
    if (twoCell == nil) {
        twoCell = [[AS_ZBPublishTwoCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:AS_ZBPublishTwoCellID];
        twoCell.backgroundColor = [UIColor whiteColor];
    }
    
    twoCell.selectMap = ^{
         NSLog(@"值为%@",_normalStr);
          // push到地图界面,这里代码没有写,只为了简化代码,验证不走dealloc的原因。
    };
    return twoCell;
    
    
}

NSLog这行代码出现了问题,有没有注意到?_normalStr实际上就是self.normalStr,所以应改成

__weak __typeof(self)weakSelf = self;
twoCell.selectMap = ^{
         NSLog(@"值为%@",weakSelf.normalStr);
    };

当然,如果你用的是用的是@synthesize的形式。那么你就要注意了,不应该写成这种如下的形式。

twoCell.selectMap = ^{
         NSLog(@"值为%@",normalStr);
    };

应该写成如下形式-核心代码展示如下


@interface AS_ZBPublishVC ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)NSString *normalStr;
@end


@implementation AS_ZBPublishVC
@synthesize normalStr;

static NSString *AS_ZBPublishTwoCellID = @"AS_ZBPublishTwoCell";
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    AS_ZBPublishTwoCell *twoCell = [tableView cellForRowAtIndexPath:indexPath]; //根据indexPath准确地取出一行,而不是从cell重用队列中取出
    if (twoCell == nil) {
        twoCell = [[AS_ZBPublishTwoCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:AS_ZBPublishTwoCellID];
        twoCell.backgroundColor = [UIColor whiteColor];
    }
    
   __weak __typeof(self)weakSelf = self;
twoCell.selectMap = ^{
         NSLog(@"值为%@",weakSelf.normalStr);
    };
    return twoCell;
    
    
}

总结:如果在block里面用到了,那么一定要用weakSelf.normalStr的形式,不应该用_normalStr或者normalStr的形式。

@synthesize的使用

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容