2017-06-16 56 views
0

我想在我的項目中啓用核心數據。由於我已經完成了我的項目,所以我錯過了在開始時啓用核心數據的選項。 任何人都可以幫我啓用它嗎? 謝謝啓用核心數據Xcode Swift

+4

的[添加核心數據與現有iPhone項目]可能的複製(HTTPS:/ /stackoverflow.com/questions/2032818/adding-core-data-to-existing-iphone-project) –

+0

https://medium.com/@MichalSverak/coredata-and-swift-3-c135822250ce – prabodhprakash

回答

-1

點擊你的應用程序目標(在左邊的窗格上它的頂部圖標和你的應用程序的名稱),然後進入「構建階段」標籤,然後點擊「鏈接二進制庫」,點擊「 +',然後找到'CoreData.framework'並將其添加到項目中

啓動核心數據選項啓用的另一個新項目。將這些方法複製到當前項目中。您可以根據您需要的方法手動逐個執行此操作,並將在您的項目中使用這些方法。另外,不要忘了添加:

import CoreData 
2

您可以直接在正在運行的項目去你的項目名稱添加核心數據右鍵點擊選擇新的文件,然後選擇數據模型形成coredata節,你有一些在AppDelegate.swift文件核心數據結構....

中的AppDelegate文件中添加以下代碼.....

import CoreData 

// MARK: - Core Data stack 

    lazy var applicationDocumentsDirectory: URL = { 
     // The directory the application uses to store the Core Data store file. This code uses a directory named "com.purpleapps.PixBoxNew.PixBox" in the application's documents Application Support directory. 
     let urls = FileManager.default.urls(for: .documentDirectory, in: .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 = Bundle.main.url(forResource: "<<YourCoredatanamehere>>", withExtension: "momd")! 
     return NSManagedObjectModel(contentsOf: 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.appendingPathComponent("SingleViewCoreData.sqlite") 
     print(url) 
     var failureReason = "There was an error creating or loading the application's saved data." 
     do { 
      let myOptions = [NSMigratePersistentStoresAutomaticallyOption: true, 
          NSInferMappingModelAutomaticallyOption: true] 
      try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: myOptions) 
     } catch { 
      // Report any error we got. 
      var dict = [String: AnyObject]() 
      dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject? 
      dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject? 

      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 
     //UNDO 
     //   var managedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) 
     var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) 
     managedObjectContext.persistentStoreCoordinator = coordinator 
     return managedObjectContext 
    }() 

    lazy var writerManagedObjectContext: 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 writerManagedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) 
     // writerManagedObjectContext.persistentStoreCoordinator = coordinator 

     // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_mocDidSaveNotification:) name:NSManagedObjectContextDidSaveNotification object:nil]; 

     NotificationCenter.default.addObserver(self, selector: #selector(AppDelegate.mocDidChangeNotification), name: NSNotification.Name.NSManagedObjectContextDidSave, object: nil) 
     return writerManagedObjectContext 
    }() 
    // MARK: - Core Data Saving support 

    func mocDidChangeNotification(_ notification : Notification){ 
     DispatchQueue.main.async { 
      self.managedObjectContext.mergeChanges(fromContextDidSave: notification) 
     } 
    } 

    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() 
      } 
     } 
    }