读写应用程序数据-CoreData
coreData数据最终的存储类型可以是:SQLite数据库、XML、二进制、内存里、自定义的数据类型。
和SQLite区别:只能取出整个实体记录,然后分解,之后才能得到实体的某个属性。
1、创建工程勾选use coreData选项。
AppDelete.swift中自动生成一些方法:
// 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.LMY.LMYCoreData" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-]
}()
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("LMYCoreData", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
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: , 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
}()
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
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// 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.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.LMY.LMYCoreData" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-]
}()
表示应用程序沙盒下的Documents目录路径。
选中coreData.xcdatamodeld文件,添加实体并命名,选中实体添加相关的属性。

可以切换Editor Style按钮查看实体的关系图。

2、为每个实体生成一个NSManagedObject子类,通过类的成员属性来访问和获取数据。选择CoreData项下面NSManagedObject subClass类型文件,生成该实体同名的类User.swift。
在User.swift对象类中添加一句代码:
//objc特性告诉编译器该声明可以在Objective-C代码中使用
@objc(User)
User对象创建以后,通过对象来使用coreData。
3、插入数据需要以下步骤:
1)通过appdelegate单例来获取管理的数据的上下文对象,操作实际内容。
//获取管理的数据上下文对象
let app = UIApplication.sharedApplication().delegate as! AppDelegate
let context = app.managedObjectContext
2)通过NSEntityDescription.insertNewObjectForEntityForName方法来创建实体对象。
3)给实体对象赋值。
4)context.save保存实体对象。
具体代码如下:
//获取管理的数据上下文对象
let app = UIApplication.sharedApplication().delegate as! AppDelegate let context = app.managedObjectContext //创建User对象
let oneUser = NSEntityDescription.insertNewObjectForEntityForName("User", inManagedObjectContext: context) as! User //对象赋值
oneUser.userID =
oneUser.userEmail = "18500@126.com"
oneUser.userPawd = "" //保存
do
{
try context.save()
}catch let error as NSError {
print("不能保存:\(error)")//如果创建失败,error 会返回错误信息
}
4、查询操作具体分为以下几步:
1)NSFetchRequest方法来声明数据的请求,相当于查询语句。
2)NSEntityDescription.entityForName方法声明一个实体结构,相当于表格结构。
3)NSPredicate创建一个查询条件,并设置请求的查询条件。
4)context.executeFetchRequest执行查询操作。
5)使用查询出来的数据。
具体代码如下:
//------- 查询
//声明数据的请求
let fetchRequest:NSFetchRequest = NSFetchRequest()
fetchRequest.fetchLimit = // 限定查询结果的数量
fetchRequest.fetchOffset = // 查询的偏移量
//声明一个实体结构
let entity:NSEntityDescription? = NSEntityDescription.entityForName("User", inManagedObjectContext: context)
//设置数据请求的实体结构
fetchRequest.entity = entity
//设置查询条件
let predicate = NSPredicate(format: "userID = '2'", "")
fetchRequest.predicate = predicate
//查询操作
do
{
let fetchedObjects:[AnyObject]? = try context.executeFetchRequest(fetchRequest)
//遍历查询的结果
for info:User in fetchedObjects as! [User] {
print("userID = \(info.userID)")
print("userEmail = \(info.userEmail)")
print("userPawd = \(info.userPawd)")
print("++++++++++++++++++++++++++++++++++++++")
}
}catch let error as NSError {
print("查询错误:\(error)")//如果失败,error 会返回错误信息
}
5、修改数据库方法,使用很简单,将查询出来的对象进行重新赋值,然后再使用context.save方法重新保存即可实现。
具体代码如下:
//----------修改
do
{
let fetchedObjects:[AnyObject]? = try context.executeFetchRequest(fetchRequest) //遍历查询出来的所有对象
for info:User in fetchedObjects as! [User] {
print("userID = \(info.userID)")
print("userEmail = \(info.userEmail)")
print("userPawd = \(info.userPawd)")
print("++++++++++++++++++++++++++++++++++++++") //修改邮箱
info.userEmail = "18500_junfei521@126.com"
//重新保存
do
{
try context.save()
}catch let error as NSError {
print("不能保存:\(error)")//如果失败,error 会返回错误信息
}
}
}
catch let error as NSError {
print("修改失败:\(error)")//如果失败,error 会返回错误信息
}
6、删除操作使用context.deleteObject方法,删除某个对象,然后使用context.save方法保存更新到数据库。
具体代码如下:
//---------删除对象
do
{
let fetchedObjects:[AnyObject]? = try context.executeFetchRequest(fetchRequest) for info:User in fetchedObjects as! [User]
{
context.deleteObject(info)
}
//重新保存-更新到数据库
do
{
try context.save()
}catch let error as NSError {
print("删除后保存失败:\(error)")//如果失败,error 会返回错误信息
} }catch let error as NSError {
print("删除后保存失败:\(error)")//如果失败,error 会返回错误信息
}
7、可以获取项目安装的路径
//获取路径
let homeDirectory = NSHomeDirectory()
print(homeDirectory)
读写应用程序数据-CoreData的更多相关文章
- 读写应用程序数据-NSUserDefault、对象归档(NSKeyedArchiver)、文件操作
ios中数据持久化存储方式一般有5种:NSUserDefault.对象归档(NSKeyedArchiver).文件操作.数据库存储(SQLite3).CoreData. 1.NSUserDefault ...
- 读写应用程序数据-SQLite3
SQLite3是嵌入到ios中的关系型数据库.对存储大规模的数据非常实用,使得不必将每个对象加到内存中. 支持NULL.INTEGER.REAL(浮点数字).TEXT(字符串和文本).BLOB(二进制 ...
- C# 读写西门子PLC数据,包含S7协议和Fetch/Write协议,s7支持200smart,300PLC,1200PLC,1500PLC
本文将使用一个gitHub开源的组件技术来读写西门子plc数据,使用的是基于以太网的TCP/IP实现,不需要额外的组件,读取操作只要放到后台线程就不会卡死线程,本组件支持超级方便的高性能读写操作 官方 ...
- python 读写三菱PLC数据,使用以太网读写Q系列,L系列,Fx系列的PLC数据
本文将使用一个gitHub开源的组件技术来读写三菱的plc数据,使用的是基于以太网的TCP/IP实现,不需要额外的组件,读取操作只要放到后台线程就不会卡死线程,本组件支持超级方便的高性能读写操作 gi ...
- java android 读写西门子PLC数据,包含S7协议和Fetch/Write协议,s7支持200smart,300PLC,1200PLC,1500PLC
本文将使用一个gitHub开源的组件技术来读写西门子plc数据,使用的是基于以太网的TCP/IP实现,不需要额外的组件,读取操作只要放到后台线程就不会卡死线程,本组件支持超级方便的高性能读写操作 gi ...
- C#读写西门子PLC数据
C#读写西门子PLC数据,包含S7协议和Fetch/Write协议,s7支持200smart,300PLC,1200PLC,1500PLC 本文将使用一个gitHub开源的组件技术来读写西门子plc数 ...
- C#读写三菱PLC数据 使用TCP/IP 协议
本文将使用一个Github开源的组件库技术来读写三菱PLC和西门子plc数据,使用的是基于以太网的TCP/IP实现,不需要额外的组件,读取操作只要放到后台线程就不会卡死线程,本组件支持超级方便的高性能 ...
- 由于检索用户的本地应用程序数据路径时出错,导致无法生成 SQL Server 的用户实例
/”应用程序中的服务器错误. 由于检索用户的本地应用程序数据路径时出错,导致无法生成 SQL Server 的用户实例.请确保该用户在此计算机上有本地用户配置文件.该连接将关闭. 堆栈跟踪: [Sql ...
- 微信小程序数据请求方法wx.request小测试
微信小程序数据请求方法 wx.request wxml文件: <view> <textarea value="{{textdata}}"/> </vi ...
随机推荐
- Hadoop2.2编程:新旧API的区别
Hadoop最新版本的MapReduce Release 0.20.0的API包括了一个全新的Mapreduce JAVA API,有时候也称为上下文对象. 新的API类型上不兼容以前的API,所以, ...
- ORA-12545:Connect failed beacuse target host or object does not exist
更换计算机名,重新启动系统后 oracle 的监听器就无法正常启动, 总是提示ORA-12545:Connect failed beacuse target host or object does n ...
- 调试MSBuild脚本
http://blogs.msdn.com/b/visualstudio/archive/2010/07/06/debugging-msbuild-script-with-visual-studio. ...
- easyui treegrid 封装(不用分页,用加载更多按钮)延迟加载加加载更多
/** * @author wsf数据加载 */ ; var intervalId = null; (function (win,$){ $.myCache = { dataCache : {},// ...
- 《C#并行编程高级教程》第7章 VS2010任务调试 笔记
没有什么好说的,主要是将调试模式下的Parallel Tasks窗体和Parallel Stacks窗体.折腾一下应该比看书效果好.(表示自己没有折腾过) 另外值得注意的是,主线程不是一个任务.所以主 ...
- ruby编程语言-学习笔记3(第4章 表达式和操作符)
4.6 操作符 了解优先级很重要 位移操作符 (0b1011)<< 1 # ==> "10110" 11 << 1 = 22 ...
- [Bhatia.Matrix Analysis.Solutions to Exercises and Problems]ExI.1.3
Use the QR decomposition to prove Hadamard's inequality: if $X=(x_1,\cdots,x_n)$, then $$\bex |\det ...
- 教您Photoshop中如何快速放大、缩小、移动图像
教您Photoshop中如何快速放大.缩小.移动图像 http://jingyan.baidu.com/article/ae97a646aaeaaebbfc461d5e.html
- [Tommas] Web测试中,各类web控件测试点总结
一 .界面检查 进入一个页面测试,首先是检查title,页面排版,字段等,而不是马上进入文本框校验 1.页面名称title是否正确 2.当前位置是否可见 您的位置:xxx>xxxx 3.文字格 ...
- eclipse svn安装
SVN插件下载地址及更新地址,你根据需要选择你需要的版本.现在最新是1.8.x Links for 1.8.x Release: Eclipse update site URL: http://sub ...