2011年11月21日月曜日

It Is Possible To Detach My Mind from Main Thread

NSThreadの
+ (void)detachNewThreadSelector:(SEL)aSelector toTarget:(id)aTarget withObject:(id)anArgument
について。

For non garbage-collected applications, the method aSelector is responsible for setting up an autorelease pool for the newly detached thread and freeing that pool before it exits. Garbage-collected applications do not need to create an autorelease pool.

The objects aTarget and anArgument are retained during the execution of the detached thread, then released. The detached thread is exited (using the exit class method) as soon as aTarget has completed executing the aSelector method.

If this thread is the first thread detached in the application, this method posts the NSWillBecomeMultiThreadedNotification with object nil to the default notification center.

ガベージコレクトされないアプリケーションでは、aSelector で与えるメソッドが新たに切り離されたスレッドのために、自動解放プールを設定して、セレクタの実行が終了する前にプールを解放する責任があります。ガベージコレクトされるアプリケーションは自動解放プールを作成する必要はありません。

切り離されたスレッドを実行している間 aTarget と anArgument が与えるオブジェクトは保持され、そのあと解放されます。切り離されたスレッドは aTarget オブジェクトの aSelector で与えるメソッドが完了するとすぐに(クラスメソッドの + (void)exit を使用して)終了します。

このスレッドがアプリケーションで最初に切り離されたスレッドの場合、このメソッドはデフォルトの通知センタに nil オブジェクトをともなって NSWillBecomeMultiThreadedNotification を投函します。


つまり
ガベージコレクションをしないアプリケーションでは、指定したセレクタ内で、自動解放プールの管理をしなさいねとのこと。

例えば
- (IBAction)saveData:(id)sender {
    
    [NSThread detachNewThreadSelector:@selector(saveBitmap)
                                                            toTarget:bitmapController
                                                       withObject:nil];
}
みたいなのがあって、ターゲットのオブジェクトでは
- (void)saveBitmap {
    
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
    /* 処理 */
    [pool drain];

}
を実装します。

また、10.5 以降ではこのクラスメソッドだけでなく NSThread のインスタンスが生成できるようになりました。NSOperation と同様の制御が可能です。

0 件のコメント:

コメントを投稿