views:

15

answers:

1

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];
    }
}
A: 

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.

Warren Burton