从核心数据删除对象时获取EXC_BAD_ACCESS。任何想法如何解决问题?可能需要阅读一些有关核心数据的原则(?)
func deleteEntity(_ entity : String) {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entity)
print("Object count: \(context.registeredObjects.count)") // prints 0 here
do {
let results = try context.fetch(fetchRequest)
for managedObject in results {
let managedObjectData : NSManagedObject = managedObject as! NSManagedObject
if !managedObjectData.isDeleted{
context.delete(managedObjectData) // EXC_BAD_ACCESS here, fetch request returns 1 item here!
}
}
try context.save()
} catch let error {
print(error)
}
}
Crashed: com.apple.main-thread
0 CoreData 0x1114c7293 -[NSManagedObjectContext(_NSInternalAdditions) _registerObject:withID:] + 35
1 CoreData 0x1114c5569 -[NSManagedObjectContext(_NSInternalAdditions) _retainedObjectWithID:optionalHandler:withInlineStorage:] + 217
2 CoreData 0x1114d0512 _PF_FulfillDeferredFault + 882
3 CoreData 0x1114dfe9e _PF_Handler_Primitive_GetProperty + 110
4 CoreData 0x1114dfca3 -[NSManagedObject(_NSInternalMethods) _newPropertiesForRetainedTypes:andCopiedTypes:preserveFaults:] + 323
5 CoreData 0x1114dfb39 -[NSManagedObject(_NSInternalMethods) _newAllPropertiesWithRelationshipFaultsIntact__] + 89
6 CoreData 0x1114dfa2b -[NSManagedObjectContext(_NSInternalChangeProcessing) _establishEventSnapshotsForObject:] + 75
7 CoreData 0x1114f7168 -[NSManagedObjectContext deleteObject:] + 136
编辑::上下文似乎有问题。我也曾尝试删除整个商店,但似乎有一件遗留下来,导致崩溃。稍后将以另一视图添加此特定项目。也许与关系有关。用调试
-com.apple.CoreData.ConcurrencyDebug 1
堆栈跟踪也显示
“一个NSManagedObject只能在单个NSManagedObjectContext中(或由其观察)。”
答案 0 :(得分:0)
我看到您的代码有几个问题……
NSManagedObjectContext.registeredObjects.count
将计算上下文中所有实体的所有对象。这可能不是您想要的(除非您的数据模型中只有一个实体)。do{...}
的任何出口。managedObjectData
似乎与managedObject
相同,但声明为非nil时,实际上它可能为nil。 (这可能是导致崩溃的原因。)context.save()
一次。但是您不应该使用该代码。取而代之的是,按照对this question的答复中给出的删除给定实体的所有对象的更好方式之一来替换它。
答案 1 :(得分:0)
删除实体所有对象的常用方法是
func deleteEntity(_ entity : String) throws {
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: entity)
let results = try context.fetch(fetchRequest)
for managedObject in results {
context.delete(managedObject)
}
try context.save()
}
但是在iOS 9 +,macOS 10.11+中,有更好的方法
func deleteEntity(_ entity : String) throws {
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: entity)
let deleteRequest = NSBatchDeleteRequest(fetchRequest: request as! NSFetchRequest<NSFetchRequestResult>)
let persistentStoreCoordinator = context.persistentStoreCoordinator!
try persistentStoreCoordinator.execute(deleteRequest, with: context)
try context.save()
}