【发布时间】:2011-09-27 09:14:28
【问题描述】:
我有一个应用程序需要用莫尔斯电码连续发出一个单词。我通过创建一个 NSThread 并使用“while 循环”在选择器内运行一些代码来做到这一点。代码如下:
@implementation MorseCode
-(void)startContinuousMorseBroadcast:(NSString *)words{
if (!(threadIsOn)) {
threadIsOn = YES; s
myThread = [[NSThread alloc] initWithTarget:self selector:@selector(threadSelector:) object:words];
[myThread start];
}
if (morseIsOn) {
morseIsOn = NO;
}
else{
morseIsOn = YES;
}
}
-(void)threadSelector:(NSString *)words{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
while (![myThread isCancelled]) {
// ///it Does some code here
} //end While
NSLog(@"Cleaning the pool");
[pool drain];
}
@end
退出应用程序时(用户按下按钮),在 applicationDidEnterBackground 中执行以下选择器:
-(void)cleanUpMorseObject{ //this is defined in the MorseCode class, same as threadSelector
if (threadIsOn) {
NSLog(@"cleanUpMorseObject, threadIsOn");
threadIsOn = NO;
morseIsOn = NO;
[myThread cancel];
[myThread release];
}
}
应用程序正确响应事件,我用 nslog 进行了检查。 然后调用 [MorseCode release]。 代码如下所示:
-(void)applicationDidEnterBackground{ //this happens in the ViewController
[theMorse cleanUpMorseObject]; //theMorse is an instance of MorseCode
[theMorse release];
}
问题:虽然我调用[myThread release]然后[theMorse release] theMorse的retainCount仍然在0以上(它不调用dealloc )。
Leaks Instrument 并没有说我有泄漏,但如果我打开和关闭应用程序大约 10 次,Iphone 最终会重置。同样在调试器中,我最终看到“收到内存警告。级别=2”。
另外,我从来没有在池耗尽之前看到 NSLog……
应用程序不在后台运行。 有任何想法吗?谢谢
【问题讨论】:
标签: iphone objective-c memory-management nsthread