objective c leaking NSNumber being retained
My application uses GPS and assigns an NSNumber instance variable every time the GPS is updated and in my last bit o开发者_开发问答f testing before release, I've discovered that it leaks a lot. I'm fairly certain I know which lines are contributing to the leak, but I can't figure how to solve it.
latitude = [[NSNumber numberWithFloat:[[coordinates objectAtIndex:0] floatValue]] retain];
This line is in my GPS update method and is run regularly. Latitude is an instance variable, and when I remove the retain, I can no longer access the variable in the other methods I need. I have the variable released in the dealloc method, but that doesn't seem to do anything.
I understand the alloc-release paradigm, but I'm still not sure how to fix this.
Before setting it, you must release the previously retained value. Otherwise, when you assign the new pointer, the previous object which is released has nothing referencing it and it can never be released.
To do this easily, I recommend setting it as a @property
and using self.latitude = [NSNumber numberWithFloat:[[coordinates objectAtIndex:0] floatValue]];
. Notice that the retain is no longer used in the assignment. This is assuming your property is set up with the retain
flag, and retains it for you.
I.e.
@property (nonatomic, retain) NSNumber *latitude
Without seeing the rest of your code its tough to say exactly how you should fix this, but a good first approach might be to try autoreleasing it like:
latitude = [[NSNumber numberWithFloat:[[coordinates objectAtIndex:0] floatValue]] autorelease];
The other thing to consider is making latitude a @property and set it to retain. This way, when you set it, it will release the previous value. Again, without knowing how you're using latitude its hard to point you in a solid direction.
精彩评论