1.创建CoreData
2.创建对应实体类
// // UserInfo.swift // // // Created by Fran on 15/7/31. // //
let APP_CORE_DATA_ENTITY_NAME_USERINFP = "UserInfo"
import Foundation import CoreData @objc(UserInfo) class UserInfo: NSManagedObject { @NSManaged var userId: String @NSManaged var name: String @NSManaged var portraitUri: String }
// 注意代码中的 @obj(ClassName) 必须要写, 属性前的 @NSManaged 也是不可或缺的
3. 操作类(增删改查)
// // UserInfoManager.swift // ECExpert // // Created by Fran on 15/7/31. // Copyright (c) 2015年 Fran. All rights reserved. // import UIKit class UserInfoManager: NSObject { private var managedObjectContext: NSManagedObjectContext! private var managedObjectModel: NSManagedObjectModel! private var persistentStoreCoordinator: NSPersistentStoreCoordinator! private override init() { super.init() } class func shareManager() -> UserInfoManager{ struct SingleManager{ static var token: dispatch_once_t = 0 static var singleManager: UserInfoManager! } dispatch_once(&SingleManager.token, { () -> Void in let manager = UserInfoManager() // 创建数据库 // 1. 实例化数据模型(将所有定义的模型都加载进来) // merge——合并 manager.managedObjectModel = NSManagedObjectModel.mergedModelFromBundles(nil) // 2. 实例化持久化存储调度,要建立起桥梁,需要模型 manager.persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: manager.managedObjectModel) // 3. 添加一个持久化的数据库到存储调度 // 3.1 建立数据库保存在沙盒的URL let basicPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true).first let filePath = basicPath!.stringByAppendingString("/").stringByAppendingString(APP_PATH_CHAT_USERINFO) let url = NSURL(fileURLWithPath: filePath) // 3.2 打开或者新建数据库文件 // 如果文件不存在,则新建之后打开 // 否者直接打开数据库 do { try manager.persistentStoreCoordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) manager.managedObjectContext = NSManagedObjectContext() manager.managedObjectContext.persistentStoreCoordinator = manager.persistentStoreCoordinator SingleManager.singleManager = manager } catch let error as NSError { KMLog("(error.localizedDescription)") } catch { fatalError() } }) return SingleManager.singleManager } func queryUserInfoById(userId: String) -> NSMutableArray{ let array = NSMutableArray() let predicate = NSPredicate(format: "userId = '(userId)'") let request = NSFetchRequest(entityName: APP_CORE_DATA_ENTITY_NAME_USERINFO) request.predicate = predicate let rs = try? managedObjectContext.executeFetchRequest(request) if rs != nil{ for u in rs!{ KMLog("(u.userId) (u.name) (u.portraitUri)") array.addObject(u) } } return array } func addUserInfo(userId: String, name: String, portraitUri: String) -> Bool{ let queryArray = queryUserInfoById(userId) if queryArray.count == 0{ let userInfo = NSEntityDescription.insertNewObjectForEntityForName(APP_CORE_DATA_ENTITY_NAME_USERINFO, inManagedObjectContext: managedObjectContext) as! UserInfo userInfo.userId = userId userInfo.name = name userInfo.portraitUri = portraitUri do { try managedObjectContext.save() return true } catch _ { return false } }else{ return updateUserInfo(userId, updateDic: ["name": name, "portraitUri": portraitUri]) } } func removeUserInfoById(userId: String) -> Bool{ var result = false let request = NSFetchRequest(entityName: APP_CORE_DATA_ENTITY_NAME_USERINFO) request.predicate = NSPredicate(format: "userId = '(userId)'") let rs = try? managedObjectContext.executeFetchRequest(request) if rs != nil{ for u in rs!{ KMLog("(u.userId) (u.name) (u.portraitUri)") managedObjectContext.deleteObject(u as! NSManagedObject) } do { try managedObjectContext.save() result = true } catch _ { result = false } } return result } func updateUserInfo(userId: String, updateDic: NSDictionary!) -> Bool{ var result = false let request = NSFetchRequest(entityName: APP_CORE_DATA_ENTITY_NAME_USERINFO) request.predicate = NSPredicate(format: "userId = '(userId)'") if updateDic != nil && updateDic.count > 0{ let rs = try? managedObjectContext.executeFetchRequest(request) if rs != nil{ for u in rs!{ KMLog("(u.userId) (u.name) (u.portraitUri)") for (key, value) in updateDic{ u.setValue(value, forKey: key as! String) } } do { try managedObjectContext.save() result = true } catch _ { result = false } } } return result } }