我不断得到malloc错误:双重释放......
按钮调用echoTime
函数。当我在计时器结束之前再次按下按钮时,它会给我malloc错误。当计时器结束后按下按钮再次启动它时,模拟器会挂起。
有谁知道以下代码有什么问题:
-(IBAction)echoTime: (id) sender {
if (gameTimer != nil) {
[gameTimer invalidate];
[gameTimer release];
}
NSInteger secs = 1 * 60;
if (secs != 0) {
NSNumber *elapsedSeconds = [[NSNumber alloc] initWithInt:secs];
NSDictionary *myDict = [NSDictionary dictionaryWithObject:elapsedSeconds forKey:@"TotalSeconds"];
gameTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(echoIt:) userInfo:myDict repeats: YES];
}
}
-(void)echoIt: (NSTimer *) timer {
NSNumber *num = (NSNumber *) [[timer userInfo] valueForKey:@"TotalSeconds"];
seconds++;
NSInteger sec = [num integerValue] - seconds;
NSInteger minutes = sec / 60;
[gameTimeLabel setText:[NSString stringWithFormat:@"%02i:%02i", minutes, sec-(60*minutes)]];
if (sec == 0) {
[self playSound:@"Horn"];
[gameTimer invalidate];
}
}
答案 0 :(得分:0)
NSNumber *elapsedSeconds = [[NSNumber alloc] initWithInt:secs];
一般来说,不要分配NSNumbers和NSDictionary(和NSArray,NSSet)总是保留它给出的对象(并在它应该时释放它们)。
尝试...
NSNumber *elapsedSeconds = [NSNumber numberWithInt:secs];
它会停止你所获得的保留周期并可能会停止崩溃。
也无关紧要但风格。
NSInteger secs = [[[timer userInfo] valueForKey:@"TotalSeconds"] intValue];
效率更高。