从CoreData中删除条目后如何处理包含CoreData Entry的NSMutableArray,显示为“<fault>”
PersonsArray:NSMutableArray =
( "<null>", "<null>", "<null>", "<MyProject.Person: 0x7ffc5257d850> (entity: Person; id: 0xd000000000040000 <x-coredata://8DD0B78C-C624-4808-9231-1CB419EF8B50/Person/p1> ; data: {\n image = nil;\n name = dustin;\n})", "<null>", "<null>", "<null>", "<null>", "<null>")
如果用户删除了CoreData Entry(entity:Person; name = dustin)
PersonsArray:NSMutableArray =
( "<null>", "<null>", "<null>", "<MyProject.Person: 0x7ffc5257d850> (entity: Person; id: 0xd000000000040000 <x-coredata://8DD0B78C-C624-4808-9231-1CB419EF8B50/Person/p1> ; data: <fault>)", "<null>", "<null>", "<null>", "<null>", "<null>")
如何检查PersonsArray
的索引插槽PersonsArray
包含此"<fault>"
以便将其返回到"<null>"
?
我的代码删除tableView中的条目(第二个VC)
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { switch editingStyle { case .Delete: appDel = UIApplication.sharedApplication().delegate as! AppDelegate context = appDel.managedObjectContext! //Could I do something like give VC2 the PersonsArray and here... //ADD Something like for ObjectIndex in 0..<PersonsArray.count { if PersonsArray[ObjectIndex] === results[indexPath.row] { PersonsArray[ObjectIndex] = NSNull() } } // then continue with the delete? context.deleteObject(results[indexPath.row] as! NSManagedObject) context.save(nil) self.viewDidLoad() default: return } }
真的没有简单的方法。 正确的答案是…不要将NSManagedObject
实例存储在数组中。 使用NSFetchedResultsController等,当你在这种情况下,或重新获取对象,以确定剩下的东西。
另一个select是通过侦听NSManagedObjectContextDidSave
通知来手动维护数组,并在从上下文中删除对象时从数组中删除对象。
使用NSFetchedResultsController
通常更容易。
更新1
在您的主视图控制器中,您可以持有对-objectID
的引用,而不是对象。 然后当你试图实现这个对象时,如果它消失了,你将得到一个nil
。 不漂亮,但可以工作。
相反,但是,您的主视图控制器应该监听NSManagedObjectContextDidSaveNotification
并在该通知中是一个-userInfo
和该属性的内部是三个NSSet
实例。 一个包含已更新的所有对象,一个用于插入的所有对象以及所有已删除的对象。 然后,您可以testing是否有任何被删除的东西在你的数组中,并将它们从你的数组中删除。