views:

62

answers:

2

So say I'm getting results from my core data request: (this is example code)

On a button press event it does:

NSMutableArray *results = [[myContext executeFetchRequest:request error:&error] mutableCopy];
myObject = (MyObject *)[mutableFetchResults1 objectAtIndex:0]; // assume that there's something in there

Now I want myObject to stick around for awhile in my program... i.e., the information contained in 'myObject' will be used in other events and such. So I have it defined in my .h file.

My question is, how do I manage memory in this case. Do I need to 'release' results or myObject at some point? Instruments is saying that this is leaking... But do you see any problems here?

A: 

You can just do a retain on the 0 index object from the results like so:

myObject = [(MyObject *)[mutableFetchResults1 objectAtIndex:0] retain];

And then you could release results right after that, myObject would hang around. You would then later need to release myObject as well.

BP
ok, but why do i need to release results... doesn't it release it automatically (i thought I only need to 'release' if i do an alloc or new or something) otherwise it's autoreleased?
Shnitzel
You take ownership of an object if you create it using a method whose name begins with “alloc” or “new” or contains “copy” (for example, alloc, newObject, or mutableCopy), or if you send it a retain message. See http://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html#//apple_ref/doc/uid/20000994-BAJHFBGH
Robot K
no kidding that's what i said.. i asked why i need to release results. i didn't take ownership of it.
Shnitzel
you need to release results as copying an object makes you the owner of the copy. alloc/new/*copy ... release
Jaroslaw Szpilewski
ahhhh ok, i didn't see the mutableCopy in there. thanks!
Shnitzel
+1  A: 

mutableCopy (and copy) returns an object with a retain count of 1 - you are the returned object's owner. so you have to release results at some time.

myObject is retained by the results array. you don't need to explicitly release it as you are not its owner.

if you're only interested in myObject I would retain it and release results as soon as possible.

Jaroslaw Szpilewski
yes, I'm only interested in myObject. so I retain it, and I release results thereafter.. BUT I still need to release myObject! (just as BP said).. you're saying it's wrong to release myObject??
Shnitzel
Please do not say "mutableCopy and copy return an object with a retain count of 1". It's not necessarily true. You should just say "you have ownership of the returned object and must therefore release it later".
JeremyP
if you don't retain myobject you must not release it. if you do retain it then you have to release it. - it's that simple. this is not a special case.
Jaroslaw Szpilewski