ios - 在 performSelectorInBackground 中将参数传递给 @selector?

标签 ios iphone objective-c cocoa-touch

我读过一篇关于@selector的文章,但我找不到我的问题的答案

我正在尝试将参数传递给 @selector。这是关于我所做的事情的简单代码:

- (void)viewDidLoad{
    [super viewDidLoad];

    NewsCell *cell = (NewsCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if (cell == nil){
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"NewsCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    NSString *string = @"image.png";

    [self performSelectorInBackground:@selector(doSomeThing::) withObject:nil];
}

-(void) doSomeThing:(UITableViewCell *)newsCell imageName:(NSString *)imageName{
    NSLog(@"newsCell: %@", newsCell);
    NSLog(@"imageName: %@", imageName);
}

我创建了新的 UITableViewCell 叫做 cell,它从另一个叫做 NewsCellnib 文件加载。 p>

并创建了名为 string 的新 string

问题是如何在performSelectorInBackground中将cellstring作为参数发送给@selector,任何想法??

谢谢..

最佳答案

您只能使用 performSelectorInBackground 传递一个参数(使用 withObject 参数)。

如果你想用两个参数在后台doSomeThing,你可以:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    [self doSomeThing:cell imageName:string];
});

顺便说一下,如果 doSomeThing 最终要进行 UI 更新,请确保将其分派(dispatch)回主队列:

-(void) doSomeThing:(UITableViewCell *)newsCell imageName:(NSString *)imageName {

    // do your slow stuff in the background here

    NSLog(@"newsCell: %@", newsCell);
    NSLog(@"imageName: %@", imageName);

    // now update your UI

    dispatch_async(dispatch_get_main_queue(), ^{
        // update your UI here
    });
}

作为最后的警告,如果你正在异步更新一个单元格,如果你想非常小心,你可能需要对异步方法时单元格可能已经滚出屏幕这一事实保持敏感完成(更糟糕的是,UITableView 可能已将该单元格重新用于表格的另一行)。因此,您可能需要检查以确保单元格仍在屏幕上。因此,传递 indexPath 参数而不是单元格,然后使用 UITableView 方法,cellForRowAtIndexPath ,不要与名称非常相似的 UITableViewDataSource 方法混淆 tableView:cellForRowAtIndexPath ,看看它是否仍然可见:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    [self doSomeThing:indexPath imageName:string];
});

然后

-(void) doSomeThing:(NSIndexPath *)indexPath imageName:(NSString *)imageName {

    // do your slow stuff in the background here

    NSLog(@"newsCell: %@", newsCell);
    NSLog(@"imageName: %@", imageName);

    // now update your UI

    dispatch_async(dispatch_get_main_queue(), ^{
        UITableViewCell *newsCell = [self.tableView cellForRowAtIndexPath:indexPath];
        if (newsCell)
        {
            // the cell is still visible, so update your UI here
        }
    });
}

关于ios - 在 performSelectorInBackground 中将参数传递给 @selector?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17278848/

相关文章:

iphone - NSFetchRequest 不显示任何内容

objective-c - 如果我以编程方式在viewDidLoad中添加控件,如何从其他方法访问它?

iphone - NSURLConnection 和保持事件状态

ios - 使用现有 Apple 帐户在 iTunes Connect 中添加 Sandbox Tester

ios - 在表格 View 单元格顶部显示指示器 View

ios - 独立渲染到多采样缓冲区和解析帧缓冲区

iphone - 电影下载器应用程序如何在 iOS 中运行?

ios - 如何在 swift 2 中单击“推送通知”时打开网址?

ios - 应用启动前的核心数据第二次迁移 - 出现 Unresolved 错误 : Domain Error

iphone - 在 UITableviewcell 中存储 boolean 值