读写应用程序数据-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 ...
随机推荐
- Linux多线程编程(不限Linux)转
——本文一个例子展开,介绍Linux下面线程的操作.多线程的同步和互斥. 前言 线程?为什么有了进程还需要线程呢,他们有什么区别?使用线程有什么优势呢?还有多线程编程的一些细节问题,如线程之间怎样同步 ...
- Android 使用 popupWindow实现弹层并操作弹层元素
需求: 点页面,出现弹层,弹层包含EditText,Button等,点击Button实现提交操作: 最终代码: private PopupWindow popupWindow ; private Ed ...
- 【Linux】理解setuid()、setgid()和sticky位
详见: http://blog.csdn.net/m13666368773/article/details/7615125 Linux SETUID机制 (1)进程运行时能够访问哪些资源或文件,不取决 ...
- 【HDOJ】1058 Humble Numbers
简单题,注意打表,以及输出格式.这里使用了可变参数. #include <stdio.h> #define MAXNUM 5845 #define ANS 2000000000 int b ...
- 【DataStructure In Python】Python模拟栈和队列
用Python模拟栈和队列主要是利用List,当然也可以使用collection的deque.以下内容为栈: #! /usr/bin/env python # DataStructure Stack ...
- 【转】JVM 基础知识
几年前写过一篇关于JVM调优的文章,前段时间拿出来看了看,又添加了一些东西.突然发现,基础真的很重要.学习的过程是一个由表及里,再由里及表的过程,所谓的“温故而知新”.而真正能走完这个轮回的人,也就能 ...
- GAC的理解及其作用
转:http://www.cnblogs.com/smallstone/archive/2010/06/29/1767508.html 一.GAC的作用 全称是Global Assembly Cach ...
- HashSet的实现原理
HashSet定义 public class HashSet<E> extends AbstractSet<E> implements Set<E>, Clonea ...
- North North West
North North West Time Limit: 10000ms, Special Time Limit:25000ms, Memory Limit:65536KB Total submit ...
- uDig介绍
一 安装配置Java平台此步骤不必多说,如果您是Java开发者可以跳过.如果您的机器上没有Java平台,那么请到http://java.sun.com下载jdk,当下最新的版本是1.6.安装jdk,请 ...