在某个应用程序上工作,该应用程序在任何用户登录时都应删除一些Core数据存储的情况-应该从数据库中删除以前的用户。结合使用删除实体;
func deleteEntity(_ entity : String) {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entity)
fetchRequest.includesPropertyValues = false
do {
let results = try self.context.fetch(fetchRequest)
for managedObject in results {
let managedObjectData : NSManagedObject = managedObject as! NSManagedObject
self.context.delete(managedObjectData)
}
try self.context.save()
} catch let error {
print(error)
}
}
...然后删除如下的sqlite文件。从用户那里获取报告,表明以前的用户保留在内存中,直到重新启动电话(!)。即使文件已删除,数据是否仍保留在内存中?代码有问题吗?
fileprivate func deleteStore(_ storeName: String) {
self.context.performAndWait { [weak self] () -> Void in
guard let stores = self?.context.persistentStoreCoordinator?.persistentStores else {return }
guard let appDelegate = self?.appDelegate else {return }
for store in stores {
if storeName == store.sqliteStoreName {
do {
// try self?.context.persistentStoreCoordinator?.remove(store)
try self?.context.persistentStoreCoordinator?.destroyPersistentStore(at: store.url!, ofType: NSSQLiteStoreType, options: nil)
try FileManager.default.removeItem(at: store.url!)
try FileManager.default.removeItem(at: store.walFileURL as URL)
try FileManager.default.removeItem(at: store.shmFileURL as URL)
if appDelegate.shouldUseInMemoryStores {
try self?.context.persistentStoreCoordinator?.addPersistentStore(ofType: NSInMemoryStoreType, configurationName: nil, at: store.url!, options: nil)
} else {
try self?.context.persistentStoreCoordinator?.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: store.url!, options: appDelegate.coreDataStoreOptions)
}
} catch let error as NSError {
DDLogError("caught error: \(error)")
}
}
}
}