Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iphone NSManagedObject - The proper way of deallocing?

I have a sub-class of NSManagedObject, most of the properties are dynamic (created by the managed object), but i have a couple of helper properties which are being created as @synthesize.

What is the correct way of releasing these objects??

- (void)didTurnIntoFault
{
     [self.randomVar release];
     [super didTurnIntoFault];
}

or

- (void)dealloc
{
     [self.randomVar release];
     [super dealloc];
}
like image 719
aryaxt Avatar asked Jan 05 '11 02:01

aryaxt


3 Answers

Override didTurnIntoFault and release them there. Managed objects aren't necessarily deallocated when they're faulted.

From the documentation:

You are discouraged from overriding dealloc or finalize because didTurnIntoFault is usually a better time to clear values—a managed object may not be reclaimed for some time after it has been turned into a fault. Core Data does not guarantee that either dealloc or finalize will be called in all scenarios (such as when the application quits); you should therefore not in these methods include required side effects (like saving or changes to the file system, user preferences, and so on).

like image 155
BoltClock Avatar answered Sep 27 '22 16:09

BoltClock


You might want to take a closer look at The Core Data Programming Guide. These two passages are of particular relevance

If you define custom instance variables, you should clean up these variables in didTurnIntoFault rather than dealloc or finalize.

and

You should typically not override dealloc or finalize to clear transient properties and other variables. Instead, you should override didTurnIntoFault.

like image 34
westsider Avatar answered Sep 27 '22 16:09

westsider


[This should be a comment really because I'm pointing out a different problem to the question, but I want the code formatting functionality].

Never do this:

[self.randomVar release];

That releases the object pointed to by the property backing ivar but does not make the pointer itself nil. This means you now potentially have a dangling pointer if the release results in the object being dealloced. Either do this:

self.randomVar = nil;

or this

[randomVar release];  // assumes the property is backed by an ivar of the same name.
randomVar = nil;      // can be omitted if you are in dealloc

The first form is preferred anywhere except in dealloc.

like image 34
JeremyP Avatar answered Sep 27 '22 17:09

JeremyP