我试图使用NSThread,所以我的显示图片可以在后台加载,所以我通过
调用它 [NSThread detachNewThreadSelector:@selector(displayPic:aURL :aURL2) toTarget:self withObject:nil];
但是当我通过2个字符串时,我将如何构建这个陈述?
由于
答案 0 :(得分:1)
简单的黑客,使用NSArray?或者使用任何其他集合,例如NSDictionary。
实施例
NSArray *extraArgs = [[NSArray alloc] initWithObjects:string1, string2, nil];
[NSThread detachNewThreadSelector:@selector(displayPic:) toTarget:self withObject:extraArgs];
[extraArgs release];
据我所知,没有正确的方法可以做到这一点。
答案 1 :(得分:1)
使用函数所需的所有参数作为参数传递NSDictionary
。
[NSThread detachNewThreadSelector:@selector(displayPic:) toTarget:self withObject:
[NSDictionary dictionaryWithObjectsAndKeys: @"http://www.example.org/a.jpg", @"aURL", @"http://www.example.org/a.jpg", @"aURL2", nil]];
在作为选择器代码传递的函数中,然后从字典中检索存储的参数:
- (void) displayPic: (NSDictionary*)args
{
NSString *aURL = [args valueForKey: @"aURL"],
*aURL2 = [args valueForKey: @"aURL2"];
//The rest of the code
//...
}
答案 2 :(得分:1)
好:
有一种方法可以异步调用通过NSOperationQueue
的对象上的任意方法,我强烈建议大多数时候在NSThreads
上使用操作队列。
根据您定位的操作系统(iPhone 3.x或iOS 4),这将是一行或一长串代码。
对于iOS 4,请注意单行(假设您有NSOperationQueue
名为queue
且您的工作人员对象名为worker
):
[queue addOperationWithBlock:^{ [worker displayPic:url1 :url2]; }];
请注意,这也适用于OS X 10.6。
3.x版本要求你要么子类NSOperation
,要么使用NSInvocationOperation
- 这本来就是我最初写的。
但事情就是这样:
如果您只想在后台预取某些内容,只需将您的工作人员修改为仅使用一个URL并将其与队列一起使用,以便添加更多这些获取者。
然后解决方案在2.x上再次变得容易:
NSInvocationOperation *workerOperation = [[NSInvocationOperation alloc] initWithTarget:worker selector:@selector(displayURL:) object:url];
[queue addOperation:workerOperation]; // retains the operation
[workerOperation release];
希望这有帮助