swiftiOS学习笔记iOS进阶指南

Core Data

2016-05-13  本文已影响169人  exialym

Core Data是用来将模型对象持久化储存的框架,可以保存XML、atomic、SQLite格式的文件。这里使用SQLite来举例。在你新建一个工程的时候,选择use Core Data,Xcode会帮你做一些准备工作。在这里一共有这么几个东西,持久化储存文件,持久化储存协调器,托管对象模型,托管对像上下文。

创建实体

Xcode会给你创建一个CoreDataTest.xcdatamodeld文件,这就是你管理你的对象的地方,新建实体,并在实体里建立你需要的属性和关系等。
建立好之后就可以让Xcode帮助你生成每个实体对应的类了:Editor -> Create NSManagedObject SubClass。对应每个实体这会生成两个Swift文件,你的每个实体在这里都变成了 NSManagedObject的子类,这也是在代码中我们使用的类。

托管对象

在AppDelegate里,Xcode会帮你做一些事情:

lazy var applicationDocumentsDirectory: NSURL = {
        // The directory the application uses to store the Core Data store file. This code uses a directory named "edu.bupt.exialym.CoreDataTest" in the application's documents Application Support directory.
        let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
        return urls[urls.count-1]
    }()
lazy var managedObjectModel: NSManagedObjectModel = {
        // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
        let modelURL = NSBundle.mainBundle().URLForResource("CoreDataTest", withExtension: "momd")!
        return NSManagedObjectModel(contentsOfURL: modelURL)!
    }()

持久化储存协调器

持久化储存器是程序访问持久化储存的桥梁。
在AppDelegate中,这个变量Xcode也创建好了:

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

在这里,定义了与此持久化储存协调器对应的托管对象模型、持久化储存文件。

托管对象上下文

在AppDelegate中,Xcode还定义了托管上下文,并指向了上面的持久化储存协调器:

lazy var managedObjectContext: NSManagedObjectContext = {
        // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
        let coordinator = self.persistentStoreCoordinator
        var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
        managedObjectContext.persistentStoreCoordinator = coordinator
        return managedObjectContext
    }()

当托管对象改变时,需要储存当前的托管对象上下文,这时你所做的修改才能保存起来,这样也为撤销和重做提供了支持。增删改查,只有查不需要保存。这个方法Xcode也在AppDelegate里生成了:

func saveContext () {
        if managedObjectContext.hasChanges {
            do {
                try managedObjectContext.save()
            } catch {
                let nserror = error as NSError
                NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
                abort()
            }
        }
    }

增删改很大程度上是在查的基础上完成的

//首先,规定获取数据的实体
let request = NSFetchRequest(entityName: "Book")
//配置查询条件,如果有需要还可以配置结果排序
let predicate = NSPredicate(format: "%K == %@", "name", nameText.text!)
request.predicate = predicate
var result:[NSManagedObject] = []
do{
    //进行查询,结果是一个托管对象数组
    result = try appDelegate.managedObjectContext.executeFetchRequest(request) as! [NSManagedObject]
} catch {}
resultText.text = ""
for item in result {
    //用键值对的方式获取各个值
    resultText.text! += "书名:\(item.valueForKey("name") as! String)  作者:\(item.valueForKey("author") as! String)\n"
}

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
//向指定实体中插入托管对象
let object:Book = NSEntityDescription.insertNewObjectForEntityForName("Book", inManagedObjectContext: appDelegate.managedObjectContext) as! Book
object.name = nameText.text
object.author = authorText.text
appDelegate.saveContext()

let request = NSFetchRequest(entityName: "Book")
if nameText.text != "" && authorText.text != "" {
    let predicate = NSPredicate(format: "%K == %@","name", nameText.text!)
    request.predicate = predicate
    var result:[NSManagedObject] = []
    do{
        result = try appDelegate.managedObjectContext.executeFetchRequest(request) as! [NSManagedObject]
    } catch {}
    if result.count != 0{
        resultText.text = ""
        for item in result {
            //获取到想要的对象,改想改的值
            item.setValue(authorText.text, forKey: "author")
            resultText.text! += "书名:\(item.valueForKey("name") as! String)  作者:\(item.valueForKey("author") as! String)\n"
        }
    }
}
appDelegate.saveContext()

let request = NSFetchRequest(entityName: "Book")
if nameText.text != "" && authorText.text != "" {
    let predicate = NSPredicate(format: "%K == %@","name", nameText.text!)
    request.predicate = predicate
    var result:[NSManagedObject] = []
    do{
        result = try appDelegate.managedObjectContext.executeFetchRequest(request) as! [NSManagedObject]
    } catch {}
    if result.count != 0{
        for item in result {
            appDelegate.managedObjectContext.deleteObject(item)
        }
    }
}
appDelegate.saveContext()
上一篇下一篇

猜你喜欢

热点阅读