Tha*_*nks 9 iphone cocoa multithreading objective-c
我有几个这样的方法调用:
[self myFoo];
[self heavyStuff]; // this one in other thread
[self myBar];
Run Code Online (Sandbox Code Playgroud)
我必须看哪些类/方法?当我搜索"线程"时,会出现很多类,方法和函数.哪一个最适合这里?
Mar*_*c W 20
你会的
[self performSelectorInBackground:@selector(heavyStuff) withObject:nil];
Run Code Online (Sandbox Code Playgroud)
请参阅Apple网站上的NSObject 参考.
Bar*_*ark 15
对于"火与忘",试试吧[self performSelectorInBackground:@selector(heavyStuff) withObject:nil].如果你有这样的多个操作,你可能想要检查NSOperation它的子类NSInvocationOperation.NSOperationQueue托管线程池,并发执行操作的数量,并包括通知或阻止方法,以告诉您何时完成所有操作:
[self myFoo];
NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(heavyStuff) object:nil];
[operationQueue addOperation:operation];
[operation release];
[self myBar];
...
[operationQueue waitUntilAllOperationsAreFinished]; //if you need to block until operations are finished
Run Code Online (Sandbox Code Playgroud)
在较低级别,您可以使用-[NSThread detachNewThreadSelector:@selector(heavyStuff) toTarget:self withObject:nil].
如果您专门针对Snow Leopard,可以使用Grand Central Dispatch:
[self myFoo];
dispatch_async(dispatch_get_global_queue(0, 0), ^{
[self heavyStuff];
dispatch_async(dispatch_get_main_queue(), ^{
[self myBar];
});
});
Run Code Online (Sandbox Code Playgroud)
但它不会在早期的系统(或iPhone)上运行,并且可能有点过分.
编辑:它从iOS 4.x开始在iPhone上运行.