HispaJavi
HispaJavi

Reputation: 1

Crash error using NSDictionary - Iphone SDK

Im using dictionary to save some positions with value "1";

/* * * header * * */

NSDictionary *Mypoints;

/* * * * * * * * */

-(void)myfunc: (float)y :(float)x{

    NSLog(@"%@",Mypoints);

    NSNumber *one = [NSNumber numberWithInt:1];
    NSString *key = [[NSString alloc] initWithFormat:@"%f,%f",y,x];

   [Mypoints setObject:one forKey:key];

    //show the value 
    NSNumber *tempNum = [Mypoints objectForKey:key];
    int i = tempNum.intValue;
    NSLog(@"Value: %i",i);

    //print all
    NSLog(@"%@",Mypoints);

}

The first time that I call this function everything is okay, it creates the dictionary and print the "array" in last line. But when I enter this function again, it crashes with no error.

I don't know what may be happening...

I solved the crash doing it:

Mypoints = [[NSMutableDictionary dictionaryWithObject:one forKey:key]retain];

I solved how to add more points:

//into viewDidLoad

Mypoints = [[NSMutableDictionary alloc] init];

//into myfunc

[Mypoints setObject:one forKey:key];

Upvotes: 0

Views: 1427

Answers (2)

martinws
martinws

Reputation: 124

Mypoints is not getting retained. So the first time it will be nil, the second time Mypoints will be pointing to memory which was freed.

Other minor issues in this code:

  1. Mypoints should be set to nil before use (I assume this is done elsewhere).
  2. Mypoints = [NSDictionary dictionaryWithObject:one forKey:key]; Your dictionary will also only contain 1 key/value pair because you are creating a new dictionary every time.
  3. NSString *key = [[NSString alloc] initWithFormat:@"%f,%f",y,x]; This will leak, as it is not being released.

// Not keen on this being a global but whatever... It needs to be initialised somewhere in this example. NSMutableDictionary* Mypoints = nil;

-(void)myfunc: (float)y :(float)x {
// This is hacky but shows the principle. if ( Mypoints == nil ) { Mypoints = [ NSMutableDictionary alloc ] initWithCapacity: 10 ]; // Or whatever you think the size might be. Don't forget to release it somewhere. }

NSNumber *one = [NSNumber numberWithInt:1]; NSString *key = [NSString stringWithFormat:@"%f,%f",y,x]; // This stops the leak since it is now already autoreleased. [ MyPoints setObject: one forKey: key ]; // Be careful no other key can have the same x and y value. //show the value NSNumber *tempNum = [Mypoints objectForKey:key]; int i = tempNum.intValue; NSLog(@"Value: %i",i); //print all NSLog(@"%@",Mypoints);

}

Upvotes: 2

Costique
Costique

Reputation: 23722

Because [NSDictionary dictionaryWithObject:one forKey:key] returns an autoreleased object, which gets released sometime between invocations of -myfunc:. The crash is obviously happening on the first line with NSLog().

Upvotes: 1

Related Questions