memory leak from numberWithInt?
I think my program is leaking memory in开发者_Go百科 the last line of this loop but i dont see why it should. Im not calling alloc. Can anyone explain this? I know it might be a really obvious answer but Im just getting started with objective C. Is it just that the numberWithInt call adds a +1 retain or something? Thanks
for (int k=0; k<=27; k++) {
NSNumber *zero= [NSNumber numberWithInt:0];
[randomUsed insertObject:zero atIndex:k];
[alphaKeys insertObject:zero atIndex:k];
}
The code that you have here doesn't have any leak.
You must think in term of ownership. You don't own zero
here since it was not returned from a alloc
or new
. Since you don't own it, you don't need to release
it.
What you're thinking is that insertObject:
is increasing the retainCount
, which is true. When you insert zero
into your arrays, randomUsed
and alphaKeys
retains your zero object. In this case, it's the arrays that own it, not you. They need to release it, not you.
If there's a leak, it's the array themselves that are leaking, not your zero
object.
Please review the cocoa memory management guide.
精彩评论