1.創(chuàng)建CoreData
2.創(chuàng)建對(duì)應(yīng)實(shí)體類
//
// 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()
// 創(chuàng)建數(shù)據(jù)庫(kù)
// 1. 實(shí)例化數(shù)據(jù)模型(將所有定義的模型都加載進(jìn)來)
// merge——合并
manager.managedObjectModel = NSManagedObjectModel.mergedModelFromBundles(nil)
// 2. 實(shí)例化持久化存儲(chǔ)調(diào)度捌蚊,要建立起橋梁龟再,需要模型
manager.persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: manager.managedObjectModel)
// 3. 添加一個(gè)持久化的數(shù)據(jù)庫(kù)到存儲(chǔ)調(diào)度
// 3.1 建立數(shù)據(jù)庫(kù)保存在沙盒的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 打開或者新建數(shù)據(jù)庫(kù)文件
// 如果文件不存在,則新建之后打開
// 否者直接打開數(shù)據(jù)庫(kù)
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
}
}