新年到了,祝大家大家羊年快乐,喜气洋洋。上一话中我们简单地介绍了一些coredata的基本知识,这一话我们通过编程来实现coredata的使用。这一话中建立的几个变量对照上一话中讲到的coredata中重要的变量,在AppDelegate中,添加如下代码:
lazy var applicationDocumentsDirectory:NSURL = { let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count - 1] as NSURL }() //官方比较推荐的写法
lazy var managedObjectModel: NSManagedObjectModel = { let modelUrl = NSBundle.mainBundle().URLForResource("Model", withExtension: "momd") return NSManagedObjectModel(contentsOfURL: modelUrl!)! }()//加载model
lazy var persistenetStoreCoordinator:NSPersistentStoreCoordinator = { var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("data.sqlite") var error: NSError? = nil var failureString = "Three was an error when creating or loading the application's saved data" if coordinator?.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil let dict = NSMutableDictionary() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's save data" dict[NSLocalizedFailureReasonErrorKey] = failureString dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) NSLog("Unsolved error\(error), \(error.userInfo)") abort()//有错误直接退出 } return coordinator!//没有错误就返回 }()//持久化
lazy var managedObjectContext:NSManagedObjectContext = { let coordinator = self.persistenetStoreCoordinator var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }()//上下文变量定义足够了之后我们来定义方法:
func saveContext(){ if let moc = self.managedObjectContext { var error:NSError? = nil if moc.hasChanges && !moc.save(&error){ NSLog("Unsolved error\(error), \(error.userInfo)") abort() } } }
一路点下去,后面的操作是自动关联的,生成的文件如下: