项目中,遇到一个内存泄漏的问题, 一直查代码, 终于找到问题。
说明:下面这段代码在一个UITableViewController中,为生成一个cell方法。
- (EvaluateCellTableViewCell *)createUgcCell
{
NSString *CellIdentifier = [[self getDetailElementHelper] getCellIdentifierString:@“cell的identifier值“];
EvaluateCellTableViewCell *cell = [[EvaluateCellTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
EvaluateCellTableViewCell *ugcCell = (EvaluateCellTableViewCell *)cell;
ugcCell.evaluateElementView.tapBlock = ^(NSIndexPath *cellIndexPath, NSUInteger tapIndex)
{
NSInteger dataIndex = [[self getDetailElementHelper] getUGCDetailIndexByIndexPath:cellIndexPath];
}
return ugcCell;
}|
上面的内存泄漏问题,主要是在self.view. 即self.tableview 引用了上面的各个 cell, 如这里的UgcCell. 而在这个cell中的tapBlock中,使用了self。即cell又引用了self这个UIViewController.所以出现了内存泄漏。
解决办法为很简单,即把self进行weak即可。
- (EvaluateCellTableViewCell *)createUgcCell
{
NSString *CellIdentifier = [[self getDetailElementHelper] getCellIdentifierString:@“cell的identifier值“];
EvaluateCellTableViewCell *cell = [[EvaluateCellTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
EvaluateCellTableViewCell *ugcCell = (EvaluateCellTableViewCell *)cell;
__weak typeof(self) _weakSelf = self;
ugcCell.evaluateElementView.tapBlock = ^(NSIndexPath *cellIndexPath, NSUInteger tapIndex)
{
NSInteger dataIndex = [[_weakSelf getDetailElementHelper] getUGCDetailIndexByIndexPath:cellIndexPath];
}
return ugcCell;
}|
接下来再研究一下,__strong typeof(_weakSelf) _strongSelf = _weakSelf; 这种情况的使用往往是在一个block中嵌入了另一个block所需要的。