创建一个简单的线程

创建线程的最简单方法是在后台调用选择器。这意味着创建一个新线程来执行选择器。接收对象可以是任何对象,而不仅仅是 self,但它需要响应给定的选择器。

- (void)createThread {
    [self performSelectorInBackground:@selector(threadMainWithOptionalArgument:)
                           withObject:someObject];
}

- (void)threadMainWithOptionalArgument:(id)argument {
    // To avoid memory leaks, the first thing a thread method needs to do is
    // create a new autorelease pool, either manually or via "@autoreleasepool".
    @autoreleasepool {
        // The thread code should be here.
    }
}