问题
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>")
if the user deletes 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>")
How can I check if a index slot of PersonsArray
contains this "<fault>"
so that I can return it to "<null>"
?
My code that deletes entry in tableView (second 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
}
}
回答1:
There really is no easy way. The right answer is ... don't store NSManagedObject
instances in an array. Use NSFetchedResultsController, etc. when you are in that situation or refetch the objects to determine what is left.
Another option is to manually maintain the array by listening for NSManagedObjectContextDidSave
notifications and removing objects from the array when they are deleted from the context.
Using a NSFetchedResultsController
is generally easier.
Update 1
In your main view controller you can hold a reference to the -objectID
instead of the object. Then when you attempt to realize the object you will get back a nil
if it is gone. Not pretty but that can work.
Instead, however, your main view controller should listen for NSManagedObjectContextDidSaveNotification
and in that notification is a -userInfo
and inside of that property are three NSSet
instances. One containing all objects that were updated, one for all that were inserted and for all that were deleted. You can then test to see if anything that was deleted was in your array and remove them from your array.
来源:https://stackoverflow.com/questions/29956065/how-to-deal-with-nsmutablearray-containing-coredata-entry-after-entry-is-deleted