开发者

malloc error and simulator crash

开发者 https://www.devze.com 2023-01-21 03:56 出处:网络
I constantly get malloc error : double freed.... The echoTime function is being called by a button. When I press the button again before the timer ends it gives me the malloc error. When I press the

I constantly get malloc error : double freed....

The echoTime function is being called by a button. When I press the button again before the timer ends it gives me the malloc error. When I press the button after the timer finished to start it again, the simulator hangs.

Does anyone know what is wrong 开发者_开发百科with the following piece of code:

-(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];
    }
}


NSNumber *elapsedSeconds = [[NSNumber alloc] initWithInt:secs];

In general dont alloc NSNumbers and a NSDictionary (and NSArray,NSSet) always retains the objects it is given (and releases them too when it should).

try...

NSNumber *elapsedSeconds = [NSNumber numberWithInt:secs];

It'll stop the retain cycle you've got and might stop the crash.

Also irrelevant but stylewise.

NSInteger secs = [[[timer userInfo] valueForKey:@"TotalSeconds"] intValue];

Is a little more efficient.

0

精彩评论

暂无评论...
验证码 换一张
取 消