建立一個簡單的執行緒

建立執行緒的最簡單方法是在後臺呼叫選擇器。這意味著建立一個新執行緒來執行選擇器。接收物件可以是任何物件,而不僅僅是 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.
    }
}