Objective-C Language                
            マルチスレッド
        
        
            
    サーチ…
簡単なスレッドを作成する
スレッドを作成する最も簡単な方法は、セレクタを「バックグラウンドで」呼び出すことです。つまり、セレクタを実行するために新しいスレッドが作成されます。受信オブジェクトは、 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.
    }
}
より複雑なスレッドを作成する
 NSThreadサブクラスを使用すると、より複雑なスレッドを実装することができます(たとえば、より多くの引数を渡すことや、関連するすべてのヘルパーメソッドを1つのクラスにカプセル化するなど)。さらに、 NSThreadインスタンスはプロパティまたは変数に保存することができ、現在の状態(まだ実行中かどうか)をNSThreadことができます。 
 NSThreadクラスはcancelと呼ばれるメソッドをサポートしています。これは任意のスレッドから呼び出すcancelができ、 cancelledプロパティをスレッドセーフな方法でYESに設定します。スレッドの実装は、 cancelledプロパティをクエリ(および/または観察)し、そのmainメソッドを終了できます。これは、ワーカースレッドを正常にシャットダウンするために使用できます。 
// Create a new NSThread subclass
@interface MyThread : NSThread
// Add properties for values that need to be passed from the caller to the new
// thread. Caller must not modify these once the thread is started to avoid
// threading issues (or the properties must be made thread-safe using locks).
@property NSInteger someProperty;
@end
@implementation MyThread
- (void)main
{
    @autoreleasepool {
        // The main thread method goes here
        NSLog(@"New thread. Some property: %ld", (long)self.someProperty);
    }
}
@end
MyThread *thread = [[MyThread alloc] init];
thread.someProperty = 42;
[thread start];
スレッドローカルストレージ
すべてのスレッドは、現在のスレッドに対してローカルな変更可能な辞書にアクセスできます。これにより、ロックを必要とせずに簡単に情報をキャッシュすることができます。各スレッドには専用の可変ディクショナリがあります。
NSMutableDictionary *localStorage = [NSThread currentThread].threadDictionary;
localStorage[someKey] = someValue;
辞書は、スレッドが終了すると自動的に解放されます。
Modified text is an extract of the original Stack Overflow Documentation
        ライセンスを受けた CC BY-SA 3.0
        所属していない Stack Overflow