Reputation: 1
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
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:
// 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
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