2011-03-29 107 views
0

我的一個自定義類有NSThread *作爲成員變量。(iphone)是一個壞主意?

我讓線程退出通過設置一個變量(isNeedToExit)。
然後在線程對象[myThread release]上調用釋放;

我希望線程先退出並釋放調用被調用。
但第二個想法是,釋放調用可能會在線程發現布爾值已更改並退出之前被調用。
(因爲線程並不經常看值是否需要退出)

@property(nonatomic,retain)NSThread * myThread;

- (void) dealloc 
{ 
    ... 
    [myThread release]; 
    myThread = nil; 
    ... 
    [super dealloc]; 
} 

- (id) initMyClass 
{ 
    if(self = [super init]) 
    { 
     ... 
     NSThread* aThread = [[NSThread alloc] initWithTarget: self selector:@selector(theThreadMain) object: nil]; 
     self.myThread = aThread; 
     [aThread release]; 
     [self.myThread start]; 
     .. 
    } 
    return self; 
} 

- (void) theThreadMain 
{ 
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; 

    // Add your sources or timers to the run loop and do any other setup.                                         
    NSRunLoop *runloop = [NSRunLoop currentRunLoop]; 
    [runloop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode]; 

    do 
    { 
     // Start the run loop but return after each source is handled.                                          
     SInt32 result = CFRunLoopRunInMode(kCFRunLoopDefaultMode, 10, YES); 

    } 
    while (self.isNeedToExit == false); 

    [pool release]; 

    SYSLOG(LOG_DEBUG, "thread exiting"); 
} 

我想移動[MyThread的版本]調用(現在在類的dealloc的),以theThreadMain的最後一行..

不知道這是正確的方式來停止一個線程時,它是一個另一個類的成員變量。

謝謝

回答

1

其實,你最初的假設是更正確的。但是,您目前的實施將無法執行,因爲dealloc將永遠不會被調用。

您的課程由NSThread保留在initWithTarget:selector:object中,直到線程執行完畢纔會被釋放。因此,只要線程正在執行,您的類實例就不會被釋放。

解決此問題的一種方法是向類中添加一個「取消」方法,以停止線程。例如:

- (void)cancel 
{ 
    isNeedToExit = YES; 
    [myThread release]; 
    myThread = nil; 
} 

這將導致線程停止,並讓你的類被釋放(一旦線程停止。)你需要確保你的類的所有用戶都知道,「取消」需要被調用在課程發佈之前。例如:

[myObject cancel]; // Stop the thread 
[myObject release]; 
myObject = nil; 

更傳統的解決方案是將NSThread簡單化。

+0

感謝您的回覆,如果我正確理解您的話,我目前的實施(上面列出的代碼)很好。由於基本上我所做的是,「myObject.isNeedToExit = YES; [myObject release];」 ,並且當線程通過isNeedToExit標誌完成時,它將再次釋放myObject並調用dealloc。最終會調用[myThread發佈]。你怎麼看? – eugene 2011-04-01 07:15:57

相關問題