我的一個自定義類有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的最後一行..
不知道這是正確的方式來停止一個線程時,它是一個另一個類的成員變量。
謝謝
感謝您的回覆,如果我正確理解您的話,我目前的實施(上面列出的代碼)很好。由於基本上我所做的是,「myObject.isNeedToExit = YES; [myObject release];」 ,並且當線程通過isNeedToExit標誌完成時,它將再次釋放myObject並調用dealloc。最終會調用[myThread發佈]。你怎麼看? – eugene 2011-04-01 07:15:57