我读过一篇关于@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
,它从另一个叫做 NewsCell
的 nib 文件加载。 p>
并创建了名为 string
的新 string
问题是如何在performSelectorInBackground中将cell
和string
作为参数发送给@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/