2016-06-13 60 views
1

早上好,核心數據是持久性後,我刪除它,並重新啓動我的應用程序

我正在使用CoreData與Swift 2.2第一次工作。此刻,我可以將對象添加到我的實體「項目」,並且在按下「刪除所有內容」按鈕後,我可以刪除所有項目。這是正確的,但是當我刪除所有對象,然後重新啓動我的應用程序時,在「刪除所有內容」操作之前,我仍然擁有相同的Core Data。

這就是我如何刪除核心數據對象

@IBAction func removeWishlist(sender: AnyObject) { 
    deleteAllData("ItemsWishlist") 
    getWishlist() 
    self.tableView.reloadData() 
} 

func deleteAllData(entity: String) { 

    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate 
    let managedContext = appDelegate.managedObjectContext 
    let fetchRequest = NSFetchRequest(entityName: entity) 
    fetchRequest.returnsObjectsAsFaults = false 

    do 
    { 
     let results = try managedContext.executeFetchRequest(fetchRequest) 
     for managedObject in results 
     { 
      let managedObjectData:NSManagedObject = managedObject as! NSManagedObject 
      managedContext.deleteObject(managedObjectData) 
      print("Deleted") 
     } 

    } catch let error as NSError { 
     print(error) 
    } 
} 

,它的工作,因爲當我按下按鈕,列表是空的,但是當我重新啓動應用程序,它再次示相同的項目像之前我按下「清除」按鈕。

這就是我的的AppDelegate與核心數據部分:

// MARK: - Core Data stack 

lazy var applicationDocumentsDirectory: NSURL = { 
    // The directory the application uses to store the Core Data store file. This code uses a directory named "-.test" in the application's documents Application Support directory. 
    let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) 
    return urls[urls.count-1] 
}() 

lazy var managedObjectModel: NSManagedObjectModel = { 
    // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. 
    let modelURL = NSBundle.mainBundle().URLForResource("wishlist", withExtension: "momd")! 
    return NSManagedObjectModel(contentsOfURL: modelURL)! 
}() 

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { 
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. 
    // Create the coordinator and store 
    let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) 
    let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") 
    var failureReason = "There was an error creating or loading the application's saved data." 
    do { 
     try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) 
    } catch { 
     // Report any error we got. 
     var dict = [String: AnyObject]() 
     dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" 
     dict[NSLocalizedFailureReasonErrorKey] = failureReason 

     dict[NSUnderlyingErrorKey] = error as NSError 
     let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) 
     // Replace this with code to handle the error appropriately. 
     // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
     NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") 
     abort() 
    } 

    return coordinator 
}() 

lazy var managedObjectContext: NSManagedObjectContext = { 
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. 
    let coordinator = self.persistentStoreCoordinator 
    var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) 
    managedObjectContext.persistentStoreCoordinator = coordinator 
    return managedObjectContext 
}() 

// MARK: - Core Data Saving support 

func saveContext() { 
    if managedObjectContext.hasChanges { 
     do { 
      try managedObjectContext.save() 
     } catch { 
      // Replace this implementation with code to handle the error appropriately. 
      // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
      let nserror = error as NSError 
      NSLog("Unresolved error \(nserror), \(nserror.userInfo)") 
      abort() 
     } 
    } 
} 

我在做什麼錯的核心數據?我該如何解決這個問題?

非常感謝,

問候。

回答

4

重新啓動應用程序後重新獲得這些對象的原因是因爲在執行所有刪除操作後沒有保存NSManagedObjectContext,因此可以將這些更改持久保存到正在使用的持久存儲中。

上下文就像一個虛擬主板。將上下文中的管理對象視爲放在桌子上玩耍的玩具。你可以移動它們,打破它們,將它們移出桌子,並帶入新的玩具。該表格是你的託管對象上下文,當你準備好時,你可以保存它的狀態。當您保存託管對象上下文的狀態時,此保存操作將傳送到上下文所連接的持久存儲協調器。然後,持久性商店協調員將信息存儲到持久性存儲,然後存儲到磁盤。

func deleteAllData(entity: String) { 

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate 
let managedContext = appDelegate.managedObjectContext 
let fetchRequest = NSFetchRequest(entityName: entity) 
fetchRequest.returnsObjectsAsFaults = false 

do 
    { 
    let results = try managedContext.executeFetchRequest(fetchRequest) 
    for managedObject in results 
    { 
     let managedObjectData:NSManagedObject = managedObject as! NSManagedObject 
     managedContext.deleteObject(managedObjectData) 
     print("Deleted") 
    } 

    } catch let error as NSError { 
    print(error) 
    } 
    appDelegate.saveContext() 
} 

爲了提高性能,您應該查看NSBatchDeleteRequest。

+0

這是一個正確的答案!非常感謝@艾哈邁德 –