CoreData --- Swift

1,创建IOS项目并选择使用CoreData,选择语言Swift
2,打开项目目录 会有一项 CoreDataDemo.xcdatamodeld ,打开它,添加 Entity
这时可以修改Entity名字(首字母需大写),然后再 Attributes (必须小写)添加数据
3,打开项目的AppDelegate,会发现创建项目时自动生成的 NSManagedObject
func applicationWillTerminate(application: UIApplication) {

// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.

// Saves changes in the application's managed object context before the application terminates.

self.saveContext()

}

// MARK: - Core Data stack

lazy var applicationDocumentsDirectory: NSURL = {

// The directory the application uses to store the Core Data store file. This code uses a directory named "com.scorpio.CoreDataDemo" in the application's documents Application Support directory.

let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)

return urls[urls.count-1] as! NSURL

}()

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("CoreDataDemo", withExtension: "momd")!

return NSManagedObjectModel(contentsOfURL: modelURL)!

}()

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {

// The persistent store coordinator for the application. This implementation creates and return 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

var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)

let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("CoreDataDemo.sqlite")

println("sql路径:\(url)")

var error: NSError? = nil

var failureReason = "There was an error creating or loading the application's saved data."

if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {

coordinator = nil

// 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

error = 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 \(error), \(error!.userInfo)")

abort()

}

return coordinator

}()

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

if coordinator == nil {

return nil

}

var managedObjectContext = NSManagedObjectContext()

managedObjectContext.persistentStoreCoordinator = coordinator

return managedObjectContext

}()

// MARK: - Core Data Saving support

func saveContext () {

if let moc = self.managedObjectContext {

var error: NSError? = nil

if moc.hasChanges && !moc.save(&error) {

// Replace this implementation 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 \(error), \(error!.userInfo)")

abort()

}

}

}

4这时可以再ViewController里添加代码

var  context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext //获取NSManagedObjectContext

// 添加数据

var info :AnyObject = NSEntityDescription.insertNewObjectForEntityForName("User", inManagedObjectContext: context!)    //获取之前所创建的Entity

// 设置数据

info.setValue(name, forKey: "name”)

info.setValue(age, forKey: “year”)

info.setValue(id, forKey: "id")

context.save(nil)   // 最后保存数据

这时候可以把 AppDelegate 中         let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("CoreDataDemo.sqlite”)

打印 url,并根据url显示路径 可以查看sqlite数据库 ,用sqlite 管理工具打开,就可以看到添加的数据了

5,下面是查找,更改,删除 数据的方法 ,感兴趣的可以一一试试

查找

var f = NSFetchRequest(entityName: "User")

var:dataArr = context.executeFetchRequest(f , error: nil)!

更改

data.setValue(tfName.text, forKey: "name")

data.setValue(tfAge.text.toInt(), forKey: "year")

data.managedObjectContext?.save(nil) // 保存对象

删除

context.deleteObject(dataArr[indexPath.row] as! NSManagedObject)

context.save(nil)

其中 data 是 NSManagedObject类型数据

context 是NSManagedObjectContext 实例化

添加,更改,删除操作时候会涉及保存操作

转载于:https://www.cnblogs.com/Scorpio-Jh/p/4682042.html

iOS CoreData简单入门 - Swift版相关推荐

  1. IOS 实现3D Touch在tableView的简单应用(swift版)

    之前记录过OC版实现3D Touch功能的小小演示,最近无事整整swift,也弄个swift版的3D Touoch... 上代码. 一.3D Touch重按主屏icon出现快捷标签有两种添加方式: 1 ...

  2. IOS CoreData 简单使用CURD

    2019独角兽企业重金招聘Python工程师标准>>> iOS在CoreData中简单封装了SQLite,让开发者不需要写sql语句就可以使用SQLite进行CURD操作. 要使用C ...

  3. 线段树简单入门 (含普通线段树, zkw线段树, 主席树)

    线段树简单入门 递归版线段树 线段树的定义 线段树, 顾名思义, 就是每个节点表示一个区间. 线段树通常维护一些区间的值, 例如区间和. 比如, 上图 \([2, 5]\) 区间的和, 为以下区间的和 ...

  4. 关东升的iOS实战系列图书 《iOS实战:入门与提高卷(Swift版)》已经上市

                承蒙广大读者的厚爱我的 <iOS实战:入门与提高卷(Swift版)>京东上市了,欢迎广大读者提出宝贵意见.http://item.jd.com/11766718 ...

  5. iOS开发swift版异步加载网络图片(带缓存和缺省图片)

    iOS开发之swift版异步加载网络图片 与SDWebImage异步加载网络图片的功能相似,只是代码比较简单,功能没有SD的完善与强大,支持缺省添加图片,支持本地缓存. 异步加载图片的核心代码如下: ...

  6. Swift版iOS游戏框架Sprite Kit基础教程下册

    Swift版iOS游戏框架Sprite Kit基础教程下册 试读下载地址:http://pan.baidu.com/s/1qWBdV0C  介绍:本教程是国内唯一的Swift版的Spritekit教程 ...

  7. 微信sdk swift版_使用Swift 4的iOS版Google Maps SDK终极指南

    微信sdk swift版 by Dejan Atanasov 通过Dejan Atanasov 使用Swift 4的iOS版Google Maps SDK终极指南 (Your ultimate gui ...

  8. Python 简单入门指北(试读版)

    本文是我小专栏中 Python 简单入门指北 一文的前半部分,如果你能坚持读完并且觉得有一定收获,建议阅读原文,只需一杯咖啡钱就可以阅读更精彩的部分,也可以订阅小专栏或者加入我的知识星球,价格都是 6 ...

  9. iOS游戏框架Sprite Kit基础教程——Swift版上册

    iOS游戏框架Sprite Kit基础教程--Swift版上册 试读下载地址:http://pan.baidu.com/s/1qWBdV0C  介绍:本教程是国内唯一的Swift版的Spritekit ...

最新文章

  1. 安装Debian 7.8 过程,以及该系统的配置过程
  2. Android 手把手教您自定义ViewGroup
  3. amd一点也不yes_A粉的狂欢,AMD显卡也翻身了,3A平台不再是笑话了,AMD YES!
  4. 有计算机信号专业吗,计算机医学图像及信号处理
  5. mongodb导入bson文件_分布式文档存储数据库之MongoDB备份与恢复
  6. java字符串计数从零还是从一,java – 计数和所有字符相同的最大字符串的起始索引...
  7. 探讨下Tag标签的数据库设计(千万级数据量) 转
  8. 电商 秒杀系统 设计思路和实现方法
  9. x264去方块滤波函数解析(二)
  10. C/C++播放音乐的函数的学习
  11. 影响应用商城搜索排名的因素
  12. PMP考试的5A好考吗?
  13. win10安装c语言不兼容,手把手还原win10系统visual c++不兼容的技巧
  14. jQuery获取或设置元素的属性值
  15. javafx控件Button
  16. 服务器显示无internet,为何我可以上网,但却显示无internet访问
  17. 读取ES Date从UTC转为北京时间
  18. HTML5七夕情人节表白网页_圣诞节3d相册(含音乐开关)_ HTML+CSS+JS 求婚 html生日快乐祝福代码网页 520情人节告白代码 程序员表白源码 抖音3D旋转相册 js烟花代码
  19. Networking
  20. .plist文件里的Bundle versions string, short 跟 Bundl

热门文章

  1. 服务器系统重置,云服务器系统重置
  2. coreboot学习3:启动流程跟踪之bootblock阶段
  3. 我的内核学习笔记3:我的platform驱动模板文件
  4. 红旗linux挂载硬盘命令,红旗6sp1修改默认挂载的硬盘分区
  5. 【kafka】Found a message larger than the maximum fetch size of this consumer on topic
  6. 【Elasticsearch】实用BM25 -第2部分:BM25算法及其变量
  7. 【Jackson】jackson 语法介绍 关键字
  8. 95-50-040-java.nio.channels-NIO-NIO之Buffer(缓冲区)
  9. 60-60-020-API-Kafka Java consumer动态修改topic订阅
  10. 【Kafka】kafka NotLeaderForPartitionException thisserver is not the leader for topic-partition