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的更多相关文章

  1. 读写应用程序数据-NSUserDefault、对象归档(NSKeyedArchiver)、文件操作

    ios中数据持久化存储方式一般有5种:NSUserDefault.对象归档(NSKeyedArchiver).文件操作.数据库存储(SQLite3).CoreData. 1.NSUserDefault ...

  2. 读写应用程序数据-SQLite3

    SQLite3是嵌入到ios中的关系型数据库.对存储大规模的数据非常实用,使得不必将每个对象加到内存中. 支持NULL.INTEGER.REAL(浮点数字).TEXT(字符串和文本).BLOB(二进制 ...

  3. C# 读写西门子PLC数据,包含S7协议和Fetch/Write协议,s7支持200smart,300PLC,1200PLC,1500PLC

    本文将使用一个gitHub开源的组件技术来读写西门子plc数据,使用的是基于以太网的TCP/IP实现,不需要额外的组件,读取操作只要放到后台线程就不会卡死线程,本组件支持超级方便的高性能读写操作 官方 ...

  4. python 读写三菱PLC数据,使用以太网读写Q系列,L系列,Fx系列的PLC数据

    本文将使用一个gitHub开源的组件技术来读写三菱的plc数据,使用的是基于以太网的TCP/IP实现,不需要额外的组件,读取操作只要放到后台线程就不会卡死线程,本组件支持超级方便的高性能读写操作 gi ...

  5. java android 读写西门子PLC数据,包含S7协议和Fetch/Write协议,s7支持200smart,300PLC,1200PLC,1500PLC

    本文将使用一个gitHub开源的组件技术来读写西门子plc数据,使用的是基于以太网的TCP/IP实现,不需要额外的组件,读取操作只要放到后台线程就不会卡死线程,本组件支持超级方便的高性能读写操作 gi ...

  6. C#读写西门子PLC数据

    C#读写西门子PLC数据,包含S7协议和Fetch/Write协议,s7支持200smart,300PLC,1200PLC,1500PLC 本文将使用一个gitHub开源的组件技术来读写西门子plc数 ...

  7. C#读写三菱PLC数据 使用TCP/IP 协议

    本文将使用一个Github开源的组件库技术来读写三菱PLC和西门子plc数据,使用的是基于以太网的TCP/IP实现,不需要额外的组件,读取操作只要放到后台线程就不会卡死线程,本组件支持超级方便的高性能 ...

  8. 由于检索用户的本地应用程序数据路径时出错,导致无法生成 SQL Server 的用户实例

    /”应用程序中的服务器错误. 由于检索用户的本地应用程序数据路径时出错,导致无法生成 SQL Server 的用户实例.请确保该用户在此计算机上有本地用户配置文件.该连接将关闭. 堆栈跟踪: [Sql ...

  9. 微信小程序数据请求方法wx.request小测试

    微信小程序数据请求方法 wx.request wxml文件: <view> <textarea value="{{textdata}}"/> </vi ...

随机推荐

  1. 用PersonalRank实现基于图的推荐算法

    今天我们讲一个下怎么使用随机游走算法PersonalRank实现基于图的推荐. 在推荐系统中,用户行为数据可以表示成图的形式,具体来说是二部图.用户的行为数据集由一个个(u,i)二元组组成,表示为用户 ...

  2. 为什么要重写equals()方法与hashCode()方法

    在java中,所有的对象都是继承于Object类.Ojbect类中有两个方法equals.hashCode,这两个方法都是用来比较两个对象是否相等的. 在未重写equals方法我们是继承了object ...

  3. IBM Rational-完整的软件工程解决方案工具集

    IBM,即国际商业机器公司,1911年创立于美国,是全球最大的信息技术和业务解决方案公司,其业务遍及全球170多个国家和地区.IBM软件分为五个部分,其中Rational系列是专门针对软件工程的软件工 ...

  4. Android开发之通过Intent启动其他App的Service

    在Android5.0以前可以通过隐式Intent方式启动其他App的Service,就跟Activity启动隐式Intent一样的. 但是在5.0以后,只能使用显示的Intent方式启动了. 启动其 ...

  5. C++中的类所占内存空间总结

    C++中的类所占内存空间总结    最近在复习c++的一些基础,感觉这篇文章很不错,转载来,大家看看! 类所占内存的大小是由成员变量(静态变量除外)决定的,成员函数(这是笼统的说,后面会细说)是不计算 ...

  6. Linux Kernel KVM 'apic_get_tmcct()'函数拒绝服务漏洞

    漏洞版本: Linux Kernel 漏洞描述: Bugtraq ID:64270 CVE ID:CVE-2013-6367 Linux Kernel是一款开源的操作系统. Linux KVM LAP ...

  7. java.lang.IllegalStateException: Fatal Exception thrown on Scheduler.Worker thread.

    最近在学习RxJava 感觉很happy ,happy的同时遇到不少问题 没办法一点一点来 上张帅图先 在使用RxJava + Retrofit 的时候 有时候接口请求参数不规范 比如 {} @For ...

  8. 可视化zookeeper的事务日志(转)

    前面提到,在zookeeper server的配置文件zoo.cfg中可以通过dataLogDir来配置zookeeper的事务日志的输出目录,这个事务日志类似于下面这样的文件: 这个文件是一个二进制 ...

  9. tcxtreelist 控制单元格变颜色,或者行变颜色

    如果控制单元格变颜色,只需要把注释的放开就可以了, 也就是判断当前列,是否是你想让变颜色的列. 如果想整行变颜色, 则只需要注释下面的就可以了. procedure TfrmwpOrderSendin ...

  10. TextField笔记

    今天写scrollPanel组件,碰到一个问题:textfield自动什么时候会调节高度. 在创建TextField的时候,我制定了文本的height属性. 之后,无论怎么设置文本,height总是不 ...