aryaxt
aryaxt

Reputation: 77596

Core Data - Memory Management?

[myArray addObject:myObject];
[object release];

In obvjective c every time you add an object with retain count of 1 to an array, you must release it right after to prevent a leak.

Does this apply to NSManagedObjects ? Because in the code above if myObject is an instance of NSManagedObject I get "EXC_BAD_ACCESS"

Upvotes: 0

Views: 330

Answers (3)

Tobias
Tobias

Reputation: 4397

Look at the code:

[myArray addObject:myObject];
[object release]; //!!!What is object?

Did you mean?

[myArray addObject:myObject];
[myObject release];

And Cocoa Memory Management Programming Guide is a must to read. If you don't want to read the whole thing the Memory Management Rules are the most important part.

In general when using Core Data you'll apply the same Memory Management Rules, but there are some caveats.

Upvotes: 0

kubi
kubi

Reputation: 49354

Please read the Memory Management Programming Guide. It will answer this question and any memory management questions you have in the future.

To directly answer this question: You must release or autorelease objects that you own. You must not release or autorelease objects you do not own. You own an object when you call retain on it or obtain the object using alloc/new/copy.

There is certainly no blanket rule about releasing an object when you add it to an array.

Upvotes: 2

Lily Ballard
Lily Ballard

Reputation: 185663

Your blanket statement about releasing objects is absolutely wrong. In fact, even thinking about the retain count of an object is wrong. If you own an object, and you are dropping your reference to the owned object, you must release it. That's the basic rule. If you don't own the object, you have no business releasing it. For more detail, read the Cocoa Memory Management Programming Guide.

As for your core question of "is memory management of Core Data objects the same as everything else?", the answer is yes. Core Data itself holds onto various objects and there's some intricacies with the faulting behavior, but the ownership rules are exactly the same as the rest of Cocoa.

Upvotes: 0

Related Questions