1


我有一个 NSOperation 在我使用的 -main 方法中[NSThread detachNewThreadSelector:@selector(aMethod:) toTarget:self withObject:anArgument];

aObject(我的 NSOperation 子类的实例变量)是对在 -main 方法内返回的自动释放数组的对象的弱引用...

-(void)main {

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    NSArray *clients = [group produceClients]; // clients array is an autorelease instance
    self->aObject = [clients objectAtIndex:3]; // a weak reference, Lets say at index three!

    [NSThread detachNewThreadSelector:@selector(aMethod:) 
                             toTarget:self 
                           withObject:@"I use this for another thing"];

    // Do other things here that may take some time

    [pool release];
}

-(void)aMethod:(NSString*)aStr {

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    // aStr object is reserved for another functionality
    // I know that I could pass a NSDictionary with a number of entries, which would be
    // retained by `detachNewThreadSelector` but then ... 
    // I wouldn't have to ask this question ! :)

    // Do several things with aObject, which is a weak reference as described above.
    NSLog(@"%@", [self->aObject.id]);
    // Is it safe ?

    [pool release];
}

我知道 NSThread 的 detachNewThreadSelector 方法保留self和 withObject: anArgument,但是 aObject 会发生什么?是否确定在执行分离线程(aMethod:) 期间会存在?自我被保留detachNewThreadSelector,这是否意味着-主线程的池将被延迟释放,因为它被保留,因此clients将存在,因此aObject将存在?
或者-main(NSOperation)线程将在-aMethod(NSThread)完成之前完成执行并释放,所以在aObject那里使用不安全?

真正的问题是:当从线程内部调用[NSThread detachNewThreadSelector:@selector(aMethod:) ...toTarget:self ...]时,最后一个线程是否被保留,其自动释放的实例(clients数组)可以安全地在aMethod( self->aObject) 中使用(让我们说通过弱引用)?

4

1 回答 1

0

您的方法似乎非常不稳定,但我不是多线程专家,所以我可能是错的。您的客户端数组位于主自动释放池中,您不能保证会等到您的 aMethod 线程完成耗尽。那这个呢:

-(void)main {

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    [NSThread detachNewThreadSelector:@selector(aMethod:) 
                             toTarget:self 
                           withObject:@"I use this for another thing"];

    [pool release];
}

-(void)aMethod:(NSString*)aStr {

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    NSArray *clients = [group produceClients]; // clients array is an autorelease instance
    self->aObject = [clients objectAtIndex:3]; // a weak reference, Lets say at index three!

    [pool release];
}

使用这种方法,您的客户端数组位于线程的自动释放池中。

于 2011-06-04T01:00:01.003 回答