codeData的简单使用swift版
2016-02-24 18:15
267 查看
CoreData的使用步骤
n1.创建模型文件相当于数据库
n2.添加实体相当表
n3.创建实体类相于模型类
n4.生成上下文 关联模型文件生成数据库
n5.保存对象到数据库
n6.从数据库获取对象
n7.更新数据
n8.删除数据
//关联上下文件,关联模型文件生成数据库
let context=NSManagedObjectContext(concurrencyType:
NSManagedObjectContextConcurrencyType.MainQueueConcurrencyType)
//模型文件
let model=NSManagedObjectModel.mergedModelFromBundles(nil)
//持久化调度器
let store=NSPersistentStoreCoordinator.init(managedObjectModel: model!)
//设置沙盒路径
let doc=NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,
NSSearchPathDomainMask.UserDomainMask,
true).last
let sqlitePath=doc!.stringByAppendingString("/company.sqlite")
//数据存储的类型和数据库存储路径
try! store.addPersistentStoreWithType(NSSQLiteStoreType, configuration:
nil, URL: NSURL.fileURLWithPath(sqlitePath), options:
nil)
context.persistentStoreCoordinator=store
//保存对象到数据库
let sb=NSEntityDescription.insertNewObjectForEntityForName("Enployee", inManagedObjectContext: context)as!
Enployee
sb.age=13
sb.name="nievvsmei"
try! context.save()
//读取信息
let request=NSFetchRequest.init(entityName:"Enployee")
let emps=try!context.executeFetchRequest(request)
for sb2 in emps{
print(sb2.age,sb2.name)
}
n1.创建模型文件相当于数据库
n2.添加实体相当表
n3.创建实体类相于模型类
n4.生成上下文 关联模型文件生成数据库
n5.保存对象到数据库
n6.从数据库获取对象
n7.更新数据
n8.删除数据
//关联上下文件,关联模型文件生成数据库
let context=NSManagedObjectContext(concurrencyType:
NSManagedObjectContextConcurrencyType.MainQueueConcurrencyType)
//模型文件
let model=NSManagedObjectModel.mergedModelFromBundles(nil)
//持久化调度器
let store=NSPersistentStoreCoordinator.init(managedObjectModel: model!)
//设置沙盒路径
let doc=NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,
NSSearchPathDomainMask.UserDomainMask,
true).last
let sqlitePath=doc!.stringByAppendingString("/company.sqlite")
//数据存储的类型和数据库存储路径
try! store.addPersistentStoreWithType(NSSQLiteStoreType, configuration:
nil, URL: NSURL.fileURLWithPath(sqlitePath), options:
nil)
context.persistentStoreCoordinator=store
//保存对象到数据库
let sb=NSEntityDescription.insertNewObjectForEntityForName("Enployee", inManagedObjectContext: context)as!
Enployee
sb.age=13
sb.name="nievvsmei"
try! context.save()
//读取信息
let request=NSFetchRequest.init(entityName:"Enployee")
let emps=try!context.executeFetchRequest(request)
for sb2 in emps{
print(sb2.age,sb2.name)
}
相关文章推荐
- The Swift Programming Language学习笔记(十七)——自动引用计数
- The Swift Programming Language学习笔记(十八)——可选链式调用
- swift init 初始化
- The Swift Programming Language学习笔记(十六)——析构过程
- The Swift Programming Language学习笔记(十五)——构造过程
- Swift学习笔记八:枚举
- swift 实现身份证最后一位校验,符合(ISO 7064:1983.MOD 11-2)标准,包括正则校验
- swift inheritace 继承
- swift 类方法
- Swift之 ? 和 !
- swift properties
- [Swift] 疑难杂症
- IOS Apps 开发(Swift)(2)——Learn the Essentials of Swift(1)
- swift2.0中文版教程
- 《从零开始学Swift》学习笔记(Day5)——我所知道的标识符和关键字
- 《从零开始学Swift》学习笔记(Day4)——用Playground工具编写Swift
- 《从零开始学Swift》学习笔记(Day3)——Swift2.0之后增加的关键字
- 《从零开始学Swift》学习笔记(Day1)——我的第一行Swift代码
- 关东升的《从零开始学Swift》第2版已经出版
- 关东升的《从零开始学Swift》第2版已经出版