Swift-->CoreData原生数据库上手操作

来源:互联网 发布:如何禁用javascript 编辑:程序博客网 时间:2024/05/23 11:45

APP开发,必不可少的就是存储数据.
CoreData是IOS原生的数据存储框架,今天我就来膜拜一下苹果杰作.

1:在创建IOS项目的时候,界面上勾选Use Core Data
这样IDE就会帮你创建CoreData的初始化代码

//MARK: 最主要的就是这个成员了...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}()

2:增

//获取AppDelegate对象let app = UIApplication.sharedApplication().delegate as! AppDelegate//拿到managedObjectContext对象var context: NSManagedObjectContext {    return self.app.managedObjectContext}
for index in 0..<10000 {    //首先通过NSEntityDescription创建一个可以插入的数据模型    let demoEntity = NSEntityDescription.insertNewObjectForEntityForName("DemoEntity", inManagedObjectContext: self.context) as! DemoEntity    //之后,进行赋值    demoEntity.age = 1.2    demoEntity.password = index    demoEntity.username = "username:\(index)"    demoEntity.time = NSDate().timeIntervalSince1970    //调用保存,插入数据库    if (try? self.context.save()) != nil {        print("保存成功\(index)")    } else {        print("保存失败\(index)")    }}//我在运行这个方法的时候,经常在中途就会崩溃...估计一下子插不了这么多的数据吧?

3:删
删除操作,需要先执行查询操作,然后才能删除对象….

//创建一个查询请求,这个请求可以设置很多参数,,比如查询条件,查询过滤,查询数量等...请看官方文档let fetchRequest = NSFetchRequest()//设置查询的数据模型fetchRequest.entity = NSEntityDescription.entityForName("DemoEntity", inManagedObjectContext: self.context)//执行查询let demoEntitys = try? self.context.executeFetchRequest(fetchRequest) as! [DemoEntity]for (index, demoEntiry) in (demoEntitys?.enumerate())! {    self.context.deleteObject(demoEntiry)//删除对象}//一定要调用保存,才会生效哦;if (try? self.context.save()) != nil {    print("删除成功:\(demoEntitys?.count)条")} else {    print("删除失败:\(index)")}//经过我的测试...这个方法,也有一定概率崩溃...好伤心

4:改
修改操作,和删除操作一样,也是需要先执行查询…然后再修改…

let fetchRequest = NSFetchRequest()fetchRequest.entity = NSEntityDescription.entityForName("DemoEntity", inManagedObjectContext: self.context)let demoEntitys = try? self.context.executeFetchRequest(fetchRequest) as! [DemoEntity]for (index, demoEntiry) in (demoEntitys?.enumerate())! {    //拿到查询结果,直接赋值    let oldName = demoEntiry.username    let newName = "angcyo" + demoEntiry.username!    demoEntiry.username = newName}//保存if (try? self.context.save()) != nil {    print("修改成功:\(demoEntitys?.count)条")} else {    print("修改失败\(index)")}//有一定几率失败...好难啊;

5:查
前面已经查询过2次了~~~

let fetchRequest = NSFetchRequest()fetchRequest.entity = NSEntityDescription.entityForName("DemoEntity", inManagedObjectContext: self.context)let demoEntitys = try? self.context.executeFetchRequest(fetchRequest) as! [DemoEntity]print("查询:\(demoEntitys?.count)条")
操作 插入1000条 插入10000条 修改全部 查询全部 删除全部 第一次 0.71秒 22.59秒 1.91秒 0.001秒 xx秒

不敢测试了…一直崩溃~~伤不起…还是Realm好用,又快,关键不崩溃.

第三方数据库框架Realm的使用传送门: http://blog.csdn.net/angcyo/article/details/52282815

源码: https://github.com/angcyo/CoreDataDemo

其他数据存储方式: http://blog.csdn.net/angcyo/article/details/52347524


至此: 文章就结束了,如有疑问: QQ群 Android:274306954 Swift:399799363 欢迎您的加入.

0 0
原创粉丝点击