x89a10
x89a10

Reputation: 691

Pointers to NSManagedObject after object delete / context save?

Can someone please explain what happens to the pointers to the NSManagedObjects after the object is deleted and the context is saved? How should I set them up so that they get set to nil automatically?

Upvotes: 1

Views: 1258

Answers (3)

Werner Kratochwil
Werner Kratochwil

Reputation: 382

I check for (managedObject.managedContext == nil). If it is nil then it was deleted. Although this is not guaranteed by Apple Documentation, it seems to be working fine with me. If you use it in different contexts or it is not saved, it will not work. See How can I tell whether an `NSManagedObject` has been deleted? for details.

Upvotes: 0

Fruity Geek
Fruity Geek

Reputation: 7381

After you delete an object, the isDeleted property will be true. After saving the context, the isDeleted will be false if you still have a reference to the managed object.

You can safely make weak references to managed objects. The weak reference will nil out automatically for you under ARC when Core Data is done with them.

Here are the three relevant paragraphs from the Core Data Programming Guide:

Core Data “owns” the life-cycle of managed objects. With faulting and undo, you cannot make the same assumptions about the life-cycle of a managed object as you would of a standard Cocoa object—managed objects can be instantiated, destroyed, and resurrected by the framework as it requires.

When a managed object is created, it is initialized with the default values given for its entity in the managed object model. In many cases the default values set in the model may be sufficient. Sometimes, however, you may wish to perform additional initialization—perhaps using dynamic values (such as the current date and time) that cannot be represented in the model.

You should typically not override dealloc to clear transient properties and other variables. Instead, you should override didTurnIntoFault. didTurnIntoFault is invoked automatically by Core Data when an object is turned into a fault and immediately prior to actual deallocation. You might turn a managed object into a fault specifically to reduce memory overhead (see “Reducing Memory Overhead”), so it is important to ensure that you properly perform clean-up operations in didTurnIntoFault.

Upvotes: 2

Mundi
Mundi

Reputation: 80265

Well, it's quite simple.

[managedObjectContext deleteObject:managedObject];
[managedObjectContext save:error];
managedObject = nil;

If you are afraid of memory leaks when deleting lots of objects, just use fast enumeration. This is pretty much guaranteed to clean up behind itself:

for (NSManagedObject *obj in fetchedObjects) {
    [managedObjectContext deleteObject:obj];
}
[managedObjectContext save:error];

Upvotes: 2

Related Questions