Iphone 在后台线程中使用int返回值执行方法
我试图通过在后台线程中执行计算来提高我的应用程序性能,但我在这方面遇到了困难。原来我一直在用Iphone 在后台线程中使用int返回值执行方法,iphone,objective-c,multithreading,Iphone,Objective C,Multithreading,我试图通过在后台线程中执行计算来提高我的应用程序性能,但我在这方面遇到了困难。原来我一直在用 [self performSelectorInBackground:@selector(calculateValue:) withObject:[words objectAtIndex:row]]; 当我的选择器是void方法时,这很好。然而,我试图做一些类似的事情,但很明显下面的代码是无效的 int value = [self performSelectorInBackground:@selecto
[self performSelectorInBackground:@selector(calculateValue:) withObject:[words objectAtIndex:row]];
当我的选择器是void方法时,这很好。然而,我试图做一些类似的事情,但很明显下面的代码是无效的
int value = [self performSelectorInBackground:@selector(calculateValue:) withObject:[words objectAtIndex:row]];
非常感谢您的帮助
已更新
这是我目前要走的路线。我不知道如何调用主线程将更新后的值从computeWordValue发送到我的cellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
int value = [self performSelectorInBackground:@selector(calculateWordValue:) withObject:[wordsSection objectAtIndex:row]];
NSString *pointValue = [[NSString alloc] initWithFormat:@"Point:%d",value];
cell.pointLabel.text = pointValue;
}
-(void)calculateWordValue:(NSString *)word {
[self performSelectorOnMainThread:@selector(computeWordValue:) withObject:word waitUntilDone:YES];
}
-(int)computeWordValue:(NSString *)word {
return totalValue; //This will be a randomly generated number
}
以下是我常用的一种方法:
-(void) calculateValue:(id) obj
{
// calculate value
[self performSelectorOnMainThread:@selector(didFinishCalculating:) withObject:[NSNumber numberWithInt:value]];
}
-(void) didFinishCalculating:(NSNumber *) val
{
// do what you need to do here
}
我认为这并不能解决你的问题,但至少应该给你一个起点
更新:
您的新代码告诉我,您实际上不需要在后台执行此操作,只需使用NSDictionary或其他工具缓存值即可。下面是一个例子:
-(int) calculateValue:(id) obj
{
if ([valuesCache objectForKey:obj] == nil)
{
// calculate value
[valuesCache setObject:[NSNumber numberWithInt:result] forKey:obj];
return result;
}
else
{
return [[valuesCache objectForKey:obj] intValue];
}
}
-performSelectorInBackground:…
无法返回您正在调用的方法的值,因为它实际上是在执行选择器之前返回的。该选择器将尽快在后台线程上执行
解决方案是异步处理方法的结果,正如Richard指出的(他的答案中的方法应该是-(void)didfinishcomputing:(NSNumber*)val
,因为只有对象才能在-performSelector:…
调用中传递):
- 在后台线程上执行选择器
- 在主线程上调用结果处理程序方法。在任何情况下,您都应该在主线程上执行此操作,因为Mac OS X和iOS中的某些东西设计为只在主线程上运行,例如GUI更新
performselectornmainthread:
我遵循了这些建议,但对于如何传回int值,我仍然有点困惑。我在上面添加了更多的代码以获得更多的上下文。这并没有解决将值返回到主线程的实际问题@Joe:请参阅ogotts的答案。当您使用委托时,它不会自动调用主线程,您必须通过[myDelegate performSelectorOnMainThread:withObject:]在主线程上显式运行它
calculateWordValue的速度/速度有多快,为什么要在后台运行它呢?它执行很多计算,我只是简化了它以便发布