ios - 当我的 UITableViewCell 不再可见时,如何取消对象中的 NSOperation?

标签 ios multithreading cocoa-touch uitableview nsoperation

是我的 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 委托(delegate)我有以下代码:

if ([movie isDownloaded])
    cell.detailTextLabel.text = movie.duration;
else
{
    cell.detailTextLabel.text = @"";

    [movie downloadInQueue:self.downloadQueue completion:^(BOOL success) {

        UITableViewCell *updateCell = [tblView cellForRowAtIndexPath:indexPath];            
        if (updateCell)
        {
            updateCell.detailTextLabel.text = movie.duration;
            [updateCell setNeedsLayout];
        }
    }];
}

调用 Movie.m 并运行此代码:

- (void)downloadInQueue:(NSOperationQueue *)queue completion:(void (^)(BOOL success))completion
{
    if (!self.isDownloading)
    {
        self.downloading = YES;

        [queue addOperationWithBlock:^{
            BOOL success = NO;

            AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:self.fileURL];
            CMTime timeduration = playerItem.duration;
            float seconds = CMTimeGetSeconds(timeduration);
            self.duration = [self timeFormatted:seconds];

            self.downloading = NO;
            self.downloaded = YES;
            success = YES;

            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                completion(success);
            }];
        }];
    }
}

当我的单元格变得可见时,我想取消 Movie 对象中的 NSOperation 如果它还没有运行 (从队列中删除它)。我知道我可以子类化 UITableViewCell 并做这样的事情:

- (void)willMoveToWindow:(UIWindow *)newWindow
{
    [super willMoveToWindow:newWindow];

    if (newWindow==nil) {
            // Cell is no longer in window so cancel from queue
    }
}

问题...如何从 UITableViewCell 委托(delegate)调用中取消我的 Movie NSOperation?使用某种委托(delegate)或 NSNotification?我需要知道单元格的 indexPath 才能从我的数组中获取正确的 Movie 对象并取消操作。

最佳答案

从 iOS 6 开始,您可以使用 UITableView Delegate protocol 的 tableView:didEndDisplayingCell:forRowAtIndexPath: 方法.当单元格从表格 View 中移除时(当它不再可见时发生),这将被调用。

- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    // Cancel operation here for cell at indexPath
}

关于ios - 当我的 UITableViewCell 不再可见时,如何取消对象中的 NSOperation?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14430254/

相关文章:

ios - 在表格 View 中使用两个不同的单元格

objective-c - delaysContentTouches 仅在特定元素上而不进行子类化?

c - 使用原子和 futexes 锁定代码时无法找到竞争条件

iphone - 使用“保留”对象泄漏

ios - iTunes 描述中的要点

ios - NSDate 给出了错误的答案(Objective-C)

ios - 在单独的类中实现 CLLocationManagerDelegate 时出现内存错误

c - 如何从 pthread_join() 获取错误代码?

c# - 多线程并行编程示例

ios - 循环添加 UIImageView Cocoa Touch