在学会了如何在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 。欢迎大家访问!
原文链接:https://www.f2er.com/sqlite/199337.html