读写应用程序数据-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 ...
随机推荐
- gdb查看虚函数表、函数地址
1. 查看函数地址 看函数在代码的哪一行,使用info line就可以看到类似下面这中输出 点击(此处)折叠或打开 (gdb) info line a.cpp:10 Line 10 of &q ...
- poj3368Frequent values(RMQ)
http://poj.org/problem?id=3368 追完韩剧 想起这题来了 想用线段树搞定来着 结果没想出来..然后想RMQ 想出来了 算是离散吧 把每个数出现的次数以及开始的位置及结束的位 ...
- 实现简单的WebPart
转:http://www.cnblogs.com/gaoweipeng/archive/2009/10/26/1589269.html 在前面的文章中,我们讲解了很多基础的内容,主要包括安装配置.简单 ...
- 从零开始学习jQuery (十一) 实战表单验证与自动完成提示插件
一.摘要 本系列文章将带您进入jQuery的精彩世界, 其中有很多作者具体的使用经验和解决方案, 即使你会使用jQuery也能在阅读中发现些许秘籍. 本文是介绍两个最常用的jQuery插件. 分别用 ...
- [OpenSource]浅谈.Net和Java互相调用的三种方式
在很多的大型系统开发中,开发工具往往不限制于同一种开发语言,而是会使用多种开发语言的混合型开发.目前Java和.Net都声称自己占85%的市场份额,不管谁对谁错,Java和.Net是目前应用开发的两个 ...
- import project后,出现Unable to get system library for the project
import project 后,出现Unable to get system library for the project. 这是因为在import 一个项目的时候,没有指定android sdk ...
- Spring面试题汇总
一.Spring最核心的功能是什么?使用Spring框架的最核心的原因是什么? Spring 框架中核心组件有三个:Core.Context 和 Beans.其中最核心的组件就是Beans, Spri ...
- nginx根据域名做http,https分发
omcat端口:8080 做好虚拟主机 参照我的另一篇文章nginx端口:80 根据域名分派 在conf/nginx.conf中的http中增加 include www.huozhe.com.conf ...
- 基于Geoserver配置多图层地图以及利用uDig来进行样式配置
在GeoServer中配置多个图层的地图相对来说很容易,其步骤为: 1. 进入geoserver 2. 配置相关的FeatureTypes 3. 配置WMS内容,进入以后,主要有以下几个地方需要命名: ...
- [综述]领域特定语言(Domain-Specific Language)的概念和意义
领域特定语言(Domain Specific Language, DSL)是一种为解决特定领域问题而对某个特定领域操作和概念进行抽象的语言.领域特定语言只是针对某个特定的领域,这点与通用编程语言(Ge ...