Core Data

25 篇文章 0 订阅

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

  • 一个托管对象模型中会有多个实体,这些实体可以储存在不同的持久化储存文件中
  • 一个持久化储存协调器只能和一个托管对象模型相连
  • 一个或多个托管对象上下文通过访问持久化对象储存协调器来访问持久化储存文件
  • 程序中操作的就是托管对象上下文

创建实体

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

托管对象

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

  • 首先它帮你获取了持久化储存的目录,这也是App一般存数据的地方:
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]
    }()
  • 接着将你的模型转换为NSManagedObject类,这里获取的CoreDataText.momd文件非常重要,它与你的工程名相对应:
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()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值