创建线程的最简单方法是“在后台”调用选择器。这意味着将创建一个新线程来执行选择器。接收对象可以是任何对象,不仅是对象,self还需要响应给定的选择器。
- (void)createThread {
[self performSelectorInBackground:@selector(threadMainWithOptionalArgument:)
withObject:someObject];
}
- (void)threadMainWithOptionalArgument:(id)argument {
// 为避免内存泄漏,线程方法需要做的第一件事是
// create a new autorelease pool, either manually or via "@autoreleasepool".
@autoreleasepool {
// 线程代码应该在这里。
}
}