Why does an unsaved managedObject lose its managedObjectContext
Asked Answered
S

1

1

Currently, I am developing an app to book cars. All booking related data are stored in an entity 'Bookings'. As some attributes of 'Bookings' or relationships between 'Bookings' and other enties are mandatory I decided to add all managedObjects of entity 'Bookings' to their own managedObjectContext. This context will also be stored in a separate variable to avoid losing it. This works fine unless I'll sign (enterprise store or adhoc) my app and deploy it. ARC is enabled.

Class Bookings interface

@interface Bookings : NSManagedObject {
@private
     NSManagedObjectContext *mContext;
}

@end

Class Bookings implementation

@implementation Bookings {

    + (Bookings *)booking {
         NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:concurrencyType];
         [context setPersistentStoreCoordinator:[self persistentStoreCoordinator]];

         Bookings *object = (Bookings*)[[NSManagedObject alloc] initWithEntity:[self entityForName:pName] insertIntoMarenagedObjectContext:context];
         [object setSomeReservationData:...];
         ...

         // here I store the context in an ivar of my booking object
         [object->mContext = context];

         return object;
    }
}

At this state the Booking object will not be saved!

Class BookingsVC

Bookings *booking = [Bookings booking];
NSLog(@"Context: %@", [booking managedObjectContext]);

Nothing saved or altered but context is null.

Console output on device (adhoc signed and deployed via iPhone-Configurator or Testflight)

... Context: (null)

Console output on simulator or device (adhoc signed but installed via Xcode)

... Context: <NSManagedObjectContext: 0x893c520>

So why does an unsaved managedObject lose its managedObjectContext and how can this be avoided? Is it a bug or the expected behavior?

Sheehy answered 5/4, 2013 at 17:5 Comment(2)
How is mContext declared?Workbag
It's declared as NSManagedObjectContext *mContext. I'll update my question.Sheehy
H
1

Your context is nullified at the end of your function. see here
Your object is disowned by the context making all its properties null, in debug mode there exists an autorelease pool keeping the context from being deallocated.

Haphazardly answered 6/4, 2013 at 5:16 Comment(1)
Thanks for the link. Didn't kown about the DEBUG/RELEASE differences either. But I can't see any relationship to my issue, as the reported behaviour (nullifying or zero values) don't match with my problem. To avoid losing the context of my object I decided to store it in an ivar. Therefore, shouldn't be the retainCount finally 1 (+1 by alloc, +1 by assigning, -1 release).Sheehy

© 2022 - 2024 — McMap. All rights reserved.