Cocoa框架中 NSObject 提供了名字中包含performSelector的方法來實現多線程編程技術。
例如:
performSelectorInBackground:withObject方法;
performSelectorOnMainThread方法;
定義這些方法要遵從以下限制:
1、這些方法運行在各自的線程里,因此必須為這些Cocoa對象創建一個自動釋放池;
2、這些方法不能有返回值,且要么沒有參數,要么只有一個參數,格式如下:
-(void) myMethod;
-(void) myMethod:(id) myObject;
當方法執行完成后,OC運行時會清理並棄掉線程。方法執行結束后,並不會通知你。
如果想要在后台執行方法,如下:
[self performSelectorInBackground:@selector(doWork) withObject:nil];
或
[self performSelectorInBackground:@selector(doWork) withObject:arugmentObject];
////后台線程處理的方法
-(void) doWork
{
NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];
[slef performSelectorOnMainThread:@selector(doneMainThread) withObject:nil waitUntilDone:NO];
[pool drain];
}
//主線程處理方法
-(void) doneMainThread
{
//.........
}
//代碼例子如下:
//.h文件
#import <Foundation/Foundation.h>
@interface SelectorTester : NSObject
- (void)runSelectors;
@end
//.m文件
#import "SelectorTester.h" @implementation SelectorTester - (void)runSelectors { [self performSelector:@selector(myBackgroundMehod1)]; [self performSelector:@selector(myBackgroundMethod2:) withObject:@"Hello Selector"]; NSLog(@"Done performing selectors"); } - (void)myBackgroundMehod1 { @autoreleasepool { NSLog(@"myBackgroundMehod1"); } } - (void)myBackgroundMethod2:(id)object { @autoreleasepool { NSLog(@"myBackgroundMethod2 %@", object); } } @end
// main文件
#import <Foundation/Foundation.h> #import "SelectorTester.h" int main(int argc, const char * argv[]) { @autoreleasepool { SelectorTester *tester = [[SelectorTester alloc] init]; [tester runSelectors]; } return 0; }