我的一个自定义类有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