Why does an unsaved managedObject lose its managedObjectContext

女生的网名这么多〃 提交于 2019-12-11 12:38:02

问题


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?


回答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.



来源:https://stackoverflow.com/questions/15839539/why-does-an-unsaved-managedobject-lose-its-managedobjectcontext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!