Ric Levy
Ric Levy

Reputation: 996

Why does releasing my CoreData context/entity make my app crash?

I have a simple CoreData app which allows you to add items to a list, displayed in a table view. When the user types in a new item, the following method is called:

- (void)addNewItem:(NSString *)item
{
    // Create a new instance of the entity managed by the fetched results controller.
    NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
    NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
    Item *newItem = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];

    [newItem setName:item];

    // Save the context.
    NSError *error = nil;
    if (![context save:&error])
    {
        //error handling code
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    [context release];
    [entity release];
    [newItem release];

The app always allows you to add one item to the list, but then crashes if you try to add a second. If I remove "[newItem release];", the app will allow you to add 4 list items, and then suddenly crash when you try to enter a fifth.

The app will only work properly if all three of those release statements at the end of the method are removed. Can anyone explain why?

Upvotes: 0

Views: 225

Answers (2)

zrzka
zrzka

Reputation: 21219

Just to clarify @BoltClock's answer. It's not about alloc, init only, but there's also new..., copy..., etc.

You should read Memory Management Guide, especially Memory Management Rules.

Upvotes: 3

BoltClock
BoltClock

Reputation: 723578

The objects are all autoreleased (because you never alloc init anything), so you're not supposed to release them yourself. It's not predictable when your app will crash as far as I can tell, but it will eventually crash.

Upvotes: 6

Related Questions