如何为UITableViewCell分配资源而不造成内存泄漏

如何为UITableViewCell分配资源而不造成内存泄漏,uitableview,avplayer,Uitableview,Avplayer,我有一个我要添加的单元格的UITableView。每个单元格包含一个图像、一个标题和一个播放器。我的实现如下 -(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath { 静态NSString*CellIdentifier=@“MyCell”; VideoFeedCell*cell=[tableView dequeueReusableCellWithIden

我有一个我要添加的单元格的UITableView。每个单元格包含一个图像、一个标题和一个播放器。我的实现如下

-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
静态NSString*CellIdentifier=@“MyCell”;
VideoFeedCell*cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
如果(单元格==nil){
NSArray*topLevelObjects=[[NSBundle mainBundle]loadNibNamed:@“MyCell”所有者:自选项:nil];
单元格=[topLevelObjects对象索引:0];
}
NSDictionary*row=[myobj objectAtIndex:indexath.row];
AVURLAsset*asset=[AVURLAsset UrlAssetTwithUrl:url选项:无];
AVPlayerItem*playerItem=[AVPlayerItem playerItemWithAsset:asset];
AVPlayer*player=[AVPlayer playerWithPlayerItem:playerItem];
AVPlayerLayer*playerLayer=[AVPlayerLayer playerLayerWithPlayer:player];
playerLayer.frame=CGRectMake(0.0,0.0,300.0,300.0);
player.actionAtItemEnd=AVPlayerActionAtItemEndNone;
[cell.myViewContainer.layer addSublayer:playerLayer];
返回单元
}

我担心的原因有很多,为每个细胞创建一个AVPlayer似乎会消耗分配的内存。我也不清楚dequeueReusableCellWithIdentifier:CellIdentifier是如何工作的。如果我在这个中间抛出一个NSLB,每当我上下滚动时,它就会被调用,这使我相信我也创建了一个AVFPLE的新实例,而这些SEAM就像一个巨大的内存泄漏。基本上,如何正确执行此操作,请分配一个类(如AVPlayer)以在UITableviewCell中使用,但请确保下次调用cellForRowAtIndexPath时不会重新分配该类。

您需要在
if(cell==nil)
块中放置任何alloc代码。因此,使用您的代码,尝试以下方法:

-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
静态NSString*CellIdentifier=@“MyCell”;
VideoFeedCell*cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
如果(单元格==nil){
NSArray*topLevelObjects=[[NSBundle mainBundle]loadNibNamed:@“MyCell”所有者:自选项:nil];
单元格=[topLevelObjects对象索引:0];
AVURLAsset*asset=[AVURLAsset UrlAssetTwithUrl:url选项:无];
AVPlayerItem*playerItem=[AVPlayerItem playerItemWithAsset:asset];
AVPlayer*player=[AVPlayer playerWithPlayerItem:playerItem];
AVPlayerLayer*playerLayer=[AVPlayerLayer playerLayerWithPlayer:player];
playerLayer.frame=CGRectMake(0.0,0.0,300.0,300.0);
player.actionAtItemEnd=AVPlayerActionAtItemEndNone;
[cell.myViewContainer.layer addSublayer:playerLayer];
}
NSDictionary*row=[myobj objectAtIndex:indexath.row];
返回单元
}

您可以清除不必要的实例:

-(void)prepareForReuse{
    [super prepareForReuse];
    [playerLayer removeFromSuperlayer];
    playerLayer = nil;
    playerItem = nil;
    asset = nil;
    player = nil;
}

我运行了代码,但问题是,它只创建了两个不同的单元格(这实际上是有意义的)。因为,只有在创建新单元格时,我才分配我的AvPlayerSet,这些单元格使用相同的AVAsset一次又一次地重复。在“if(cell==nil)”之外,您需要为播放器设置新的playerItem。使用“[player replaceCurrentItemWithPlayerItem:newItem]”