CoreData實踐(三)——插入資料並使用SQLite Professional檢視

乞力馬紮羅的雪CYF發表於2015-09-17

     在學會了如何在Xcode中設計資料庫的結構之後,我們就要程式碼實現插入一條資料。

(1)程式碼實現如下:

import UIKit
import CoreData

class ViewController: UIViewController {

  override func viewDidLoad() {
    super.viewDidLoad()

    
    var context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
    
    
    
    var row:AnyObject = NSEntityDescription.insertNewObjectForEntityForName("Users", inManagedObjectContext: context!)
    row.setValue("Robert", forKey: "name")
    row.setValue(23, forKey: "age")
    context?.save(nil)
    
    
    println("Run Here")
    
  }

  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }


}

(2)注意,一定要匯入CoreData。

(3)在電腦上安裝SQLite Professional,用於檢視SQLite資料庫。我已經放到雲盤上,大家可以下載 http://pan.baidu.com/s/1ntEeJup   。然後安裝就可以 了。

(4)在AppDelegate.swift的自動生成的一個方法中,使用println()方法列印url,可以找到程式生成的資料庫檔案的位置:

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
      // The persistent store coordinator for the application. This implementation creates and return 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
      var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
      let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("UsingData.sqlite")
    
    
    println(url)
    
    
      var error: NSError? = nil
      var failureReason = "There was an error creating or loading the application's saved data."
      if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
          coordinator = nil
          // 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
          error = 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 \(error), \(error!.userInfo)")
          abort()
      }
      
      return coordinator
  }()

(5)然後列印出的地址中會有三個資料庫檔案,使用SQLite Professional開啟即可。裡面就可以看到表中的資料了。是不是很方便呢?




github主頁:https://github.com/chenyufeng1991  。歡迎大家訪問!


相關文章