简体   繁体   English

即使已删除该对象,也要使其保持活动状态

[英]Keep alive nsmangedobject even if it has been deleted

I have a controller that presenting objects, some times the during showing this page the some of the objects are deleted. 我有一个呈现对象的控制器,有时在显示此页面期间,某些对象被删除。 and than , if we try to use this object - all properties are nil. 并且,如果我们尝试使用此对象,则所有属性均为nil。

Is there way to use copy NSMangedobject without connecting him to the real data base as a free object. 有没有一种方法可以使用副本NSMangedobject而不将其作为自由对象连接到真实数据库。 so when the original object will be deleted , this object will be stable and full of data? 因此,当原始对象将被删除时,该对象将稳定并且充满数据吗?

Thanks 谢谢

It sounds like you want to create a new NSManagedObjectContext for this controller. 听起来您想为此控制器创建一个新的NSManagedObjectContext You need to do it somewhere that you have access to to original context or its persistent store coordinator. 您需要在可以访问原始上下文或其持久性存储协调器的位置进行操作。 You can do this in prepareForSegue:sender: if you load the view controller via a storyboard segue. 您可以在prepareForSegue:sender:执行此操作prepareForSegue:sender:如果通过情节提要segue加载视图控制器。

The controller needs to load its objects from this context. 控制器需要从此上下文加载其对象。 You can't pass it objects you fetched using the original context. 您无法将使用原始上下文获取的对象传递给它。 Instead, ask each of those original objects for its objectID and use those ids to create new managed objects using the new context. 而是向每个原始对象询问其objectID并使用这些ID使用新的上下文创建新的托管对象。 Create all of the new objects immediately and access a persistent property of each (to un-fault the objects). 立即创建所有新对象,并访问每个对象的持久属性(取消故障对象)。 The new controller must keep a strong reference to each of these objects because the context doesn't necessarily retain them. 新的控制器必须对这些对象中的每一个都保持强烈的引用,因为上下文不一定会保留它们。

As long as you don't send refreshObject:mergeChanges: or mergeChangesFromContextDidSaveNotification: to the controller's private context, all of the objects should remain valid and their properties should not change. 只要您不将refreshObject:mergeChanges:mergeChangesFromContextDidSaveNotification:发送到控制器的私有上下文,所有对象都应保持有效,并且其属性也不应更改。

It feels like you use core data objects and some kind of tableview. 感觉就像您在使用核心数据对象和某种表视图。 Use nsfetchedresultscontroller and you will forget about sync problem. 使用nsfetchedresultscontroller,您将忘记同步问题。 btw, it is not safe to keep somewhere managedObjects. 顺便说一句,将某个对象保留在某个托管对象中并不安全。 possible you can copy and set managedObjectContext property to nil to make it separate from the db but these objects will be not up-to-date then. 可能您可以将ManagedObjectContext属性复制并设置为nil,以使其与数据库分开,但这些对象将不是最新的。

If you just want to keep a reference alive for runtime, you would just set a strong reference (eg @property (nonatomic, retain) ). 如果您只是想保持运行时的引用有效,则只需设置一个强引用(例如@property (nonatomic, retain) )。 If this isn't enough, you can call [id<NSCopying> copy] 如果这还不够,可以调用[id<NSCopying> copy]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM