Question

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];
}
Was it helpful?

Solution

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).

OTHER TIPS

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.

[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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top