In my Core Data Entity Favorite
, I am appending Strings to its Attribute fav
.
When I look up a fav
object based on String name and try to it, it is not deleting the entry, but instead is setting that object's fav = nil
时,它不是删除条目,而是设置该对象的fav = nil
Here is my code:
let managedContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext!
let favoriteFetchRequest = NSFetchRequest(entityName:"Favorite")
let predicate = NSPredicate(format: "fav == %@", "snowboarding")
favoriteFetchRequest.predicate = predicate
let fetchedEntities = managedContext.executeFetchRequest(favoriteFetchRequest, error: nil) as! [NSManagedObject]
for entity in fetchedEntities {
managedContext.deleteObject(entity)
if !managedContext.save(&error) {
println("Could not save \(error)")
}
}
When I rerun the app and have all Entity data display, the log shows:
<NSManagedObject: 0x7fc8b0d1e4f0> (entity: Favorite; id: 0xd000000000080000 <x-coredata://8984EF48-71AF-4B87-AA59-EE5999038369/Favorite/p2> ; data: {
fav = nil;})
This is turn creates a whole bunch of nil
entries and the Core Data is never empty (as I'd like it to be at times). What am I doing wrong? How do I delete the entire object?
Whenever I do anything with CoreData
, I take care of all the transactions before saving. Adding new Entities
, saving new Entity
attributes, etc. (Well, I shouldn't say all , but in most cases when I'm doing an update)
I'm not sure if this will fix it but try moving your
if !managedContext.save(&error) {
println("Could not save \(error)")
}
Out of the for
loop and instead have it read:
for entity in fetchedEntities {
managedContext.deleteObject(entity)
}
if !managedContext.save(&error) {
println("Could not save \(error)")
}
The rest of the code looks fine so this is the only thing I can blatantly see that differs from how I usually update my CoreData
entries. Let me know if that solves anything.
EDIT: A little bug investigation you could as well is after the for
loop, access the managedContext
's deletedObjects
property and check the count
of that NSSet
and see if it is actually registering those objects to be deleted.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.