2

我有一个要添加单元格的 UITableView。每个单元格包含一个图像、一个标题和一个 AVPlayer。我正在执行如下

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *CellIdentifier = @"MyCell";
    VideoFeedCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"MyCell" owner:self options:nil];
        cell = [topLevelObjects objectAtIndex:0];
    }
    NSDictionary *row = [myobj  objectAtIndex:indexPath.row];

    AVURLAsset *asset = [AVURLAsset URLAssetWithURL:url options:nil];
    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];
    return cell
}

我担心的原因有很多,为每个单元创建一个 AVPlayer 似乎会占用大量内存。我也不清楚 dequeueReusableCellWithIdentifier:CellIdentifier 是如何工作的。如果我在这中间抛出一个 NSLog,每次我上下滚动时都会调用它,这让我相信我也创建了一个新的 AVPlayer 实例,这就像一个巨大的内存泄漏。基本上,我如何正确地执行此操作,分配一个类(如 AVPlayer)以在 UITableviewCell 中使用,但确保在下次调用 cellForRowAtIndexPath 时不会重新分配它。

4

2 回答 2

1

您需要将任何分配代码放入if (cell == nil)块中。所以拿你的代码,试试这个:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *CellIdentifier = @"MyCell";
    VideoFeedCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"MyCell" owner:self options:nil];
        cell = [topLevelObjects objectAtIndex:0];
        AVURLAsset *asset = [AVURLAsset URLAssetWithURL:url options:nil];
        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:indexPath.row];
    return cell
}
于 2013-02-19T07:26:46.583 回答
0

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

-(void)prepareForReuse{
    [super prepareForReuse];
    [playerLayer removeFromSuperlayer];
    playerLayer = nil;
    playerItem = nil;
    asset = nil;
    player = nil;
}
于 2015-09-15T19:22:10.880 回答