为什么未保存的managedObject丢失其managedObjectContext [英] Why does an unsaved managedObject lose its managedObjectContext

查看:46
本文介绍了为什么未保存的managedObject丢失其managedObjectContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我正在开发一个用于预订汽车的应用程序.所有与预订有关的数据都存储在实体"Bookings"中.由于预订"的某些属性或预订"与其他实体之间的关系是强制性的,因此我决定将实体预订"的所有托管对象添加到其自己的ManagedObjectContext中.该上下文也将存储在单独的变量中,以避免丢失它.除非我签署(企业商店或即席存储)我的应用程序并进行部署,否则此方法将正常工作.ARC已启用.

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.

班级预订界面

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

@end

舱位预订实施

@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!

班级预订VC

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

未保存或更改任何内容,但上下文为空.

Nothing saved or altered but context is null.

在设备上的控制台输出(通过iPhone-Configurator或Testflight进行临时签名和部署)

... Context: (null)

在模拟器或设备上的控制台输出(临时签名但通过Xcode安装)

... Context: <NSManagedObjectContext: 0x893c520>

那么,为什么未保存的managedObject会丢失其managedObjectContext,又该如何避免呢?是错误还是预期的行为?

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

推荐答案

您的上下文在函数末尾被取消.看到这里
您的对象将被上下文取消所有权,使其所有属性都为空,在调试模式下,将存在一个自动释放池,以防止释放上下文.

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.

这篇关于为什么未保存的managedObject丢失其managedObjectContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆