我有一个nsthread,在这个之内的while循环。它从主方法的“线程安全”队列中获取对象。当我离开包含此nsthread对象的UIViewController时,我调用nsthread cancel方法,但它不会停止,因为它被“queueLock”NSCondition锁定。当我回到这个UIViewController时,会创建一个新的nsthread,并将这些对象组成队列,但是前一个线程仍然退出,并且它们都尝试使用队列中的同一个对象,这会导致内存管理问题。我的问题是当我离开UIViewController时应该如何阻止这个线程。iOS - Objective-C - 如何在等待时停止NSThread?
NSThread主要方法:
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
while ([self isCancelled] == NO) {
RenderRequest *renderRequest = [queue get];
[self doRender:renderRequest];
[renderRequest release];
}
[pool drain];
这是队列类的get方法:
- (id) get {
id toRet = nil;
[queueLock lock];
@try {
while ([queueContents count] == 0) {
[queueLock wait];
}
toRet = [queueContents lastObject];
[queueContents removeLastObject];
}
@finally {
[queueLock unlock];
return toRet;
}
}
谢谢!
谢谢,我会试一试。 – 2012-03-29 20:29:33
感谢您的写作!我用这个很好的演示来了解NSThread以及如何排队数据。虽然现在每个人都指向GCD,但我认为记住NSThread'亲手做'选项很重要。 – LEO 2013-09-15 01:58:34