应用程序离不开数据的永久存储,有两种方式实现存储:数据库和文本文件。

作为存储管理器,最基本的功能就是增删改查了。

CoreData

1、插入

AppDelegate *app = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [app managedObjectContext];
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:@"entityname" inManagedObjectContext:context];
[newManagedObject setValue:value forKey:@"propertyname"];
NSError *error;
if (![context save:&error]) { // Handle the error…
}

2、查询

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSManagedObjectContext *managedObjectContext = appDelegate.managedObjectContext;
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Hero" inManagedObjectContext:managedObjectContext];
NSSortDescriptor *sortDescriptor1 = [[NSSortDescriptor alloc]initWithKey:@”name” ascending:YES];
NSSortDescriptor *sortDescriptor2 = [[NSSortDescriptor alloc]initWithKey:@”secretIdentity” ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc]initWithObjects:sortDescriptor1, sortDescriptor2, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
[fetchRequest setEntity:entity];
[fetchRequest setFetchBatchSize:];
NSArray *objecs = [context executeFetchRequest: fetchRequest error:&error];
if(objets==nil || error != nil){
  //做处理
}

3、修改

-(void)applicationWillResignActive:(NSNotification *)notification{
NSLog(@"applicationWillResignActive");
//创建托管对象上下文
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"User" inManagedObjectContext:context];
[request setEntity:entityDescription]; NSManagedObject *user = nil;
NSError *error;
NSArray *objets = [context executeFetchRequest:request error:&error];
if(objets==nil){
NSLog(@"There has a error!");
//做错误处理
}
if([objets count]>){
//非第一次,更新数据
NSLog(@"更新操作");
user = [objets objectAtIndex:];
}else{
NSLog(@"插入操作");
//第一次保存,插入新数据
user = [NSEntityDescription insertNewObjectForEntityForName:@"User" inManagedObjectContext:context];
}
[user setValue:self.serverIp.text forKeyPath:@"serverIp"];
[user setValue:self.userName.text forKeyPath:@"userName"];
[context save:&error];
}

4、删除

NSManagedObjectContext *managedObjectContext = appDelegate.managedObjectContext;
[context deleteObject:[objecs objectIndex:index];
NSError *error;
if (![context save:&error]) {
NSLog(@”Unresolved error %@, %@”, error, [error userInfo]);
exit(-); // Fail
}

5、数据迁移

当程序变化时,在很多简单的情况下,Coredata提供了轻量级的自动数据迁移,比如以下三个情况可以通过开启CoreData自动迁移实现:
1.简单的增加一个字段
2.把一个必填字段改为可选字段
3.把可选字段改为必填字段(但一定要定义默认值)

文本读写

  文本是存储在外存上的字节序列,进程需要在内存中创建缓冲区(通常称之为“流”或“stream”,NSData和NSOutputStream的实例都对应“流”的概念),然后再进行读写,不过NSData一般配合NSArchiver一起使用来存储对象,对于文本读写、网络传输,一般用NSOutputStream来作为缓冲区,一个缓冲区对象封装一些读写方法告诉线程如何进行读写。

  在下面的例子中,进程调用inputData将学生数据插入对象关系数据库,在调用queryStudents读取学生信息,暂存在输出流NSOutputStream的实例中,然后写入CSV文本文件。

- (void)createFile:(NSString *)fileName;
- (void)exportCSV:(NSString *)fileName;
- (NSArray *)queryStudents; //控件关联方法
- (IBAction)inputData:(id)sender { AppDelegate *app = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = app.managedObjectContext; Student *stu = (Student *)[NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:context];
stu.name = self.nameTextField.text;
stu.num = self.numTextField.text; NSError *error = nil;
[context save:&error]; self.nameTextField.text = @"";
self.numTextField.text = @"";
} - (IBAction)makeCSV:(id)sender { NSArray *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDirectory, YES);
NSString *docementDir = [documents objectAtIndex:];
NSString *filePath = [docementDir stringByAppendingPathComponent:@"student.csv"];
NSLog(@"filePath = %@", filePath); [self createFile:filePath];
[self exportCSV:filePath];
} //私有方法
- (void)createFile:(NSString *)fileName { NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager removeItemAtPath:fileName error:nil];
if (![fileManager createFileAtPath:fileName contents:nil attributes:nil]) {
NSLog(@"不能创建文件");
} } - (void)exportCSV:(NSString *)fileName { NSOutputStream *output = [[NSOutputStream alloc] initToFileAtPath:fileName append:YES];
[output open]; if (![output hasSpaceAvailable]) {
NSLog(@"没有足够可用空间");
} else {
NSString *header = @"学好,姓名\n";
const uint8_t *headerString = (const uint8_t *)[header cStringUsingEncoding:NSUTF8StringEncoding];
NSInteger headerLength = [header lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
NSInteger result = [output write:headerString maxLength:headerLength];
if (result <= ) {
NSLog(@"写入错误");
} NSArray *students = [self queryStudents];
for (Student *stu in students) {
NSString *row = [NSString stringWithFormat:@"%@,%@\n", stu.num, stu.name];
const uint8_t *rowString = (const uint8_t *)[row cStringUsingEncoding:NSUTF8StringEncoding];
NSInteger rowLength = [row lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
result = [output write:rowString maxLength:rowLength];
if (result <= ) {
NSLog(@"无法写入内容");
}
}
}
[output close];
} - (NSArray *)queryStudents { NSEntityDescription *entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:self.managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
fetchRequest.entity = entity;
NSArray *students = [self.managedObjectContext executeFetchRequest:fetchRequest error:nil];
return students;
}

Cocoa Touch(二):数据存储CoreData, NSKeyArchiver, NSOutputStream, NSUserDefaults的更多相关文章

  1. Base-Android快速开发框架(二)--数据存储之SharedPreferences

    对于App开发者,抽象来说,其实就是将数据以各种各样的方式展示在用户面前以及采集用户的数据.采集用户的数据包括用户的输入.触摸.传感器等,展示的数据通过网络来源于各业务系统,以及用户的 输入数据.在这 ...

  2. 数据存储之偏好设置NSUserDefaults

    NSUserDefaults做数据存储也是比较常用,适合轻量级的本地数据存储,读取也很方便. 一.支持的数据类型如下图(NSString.NSArray.NSDictionary.NSData.NSI ...

  3. 数据存储简单了解(NSUserDefaults)

    数据存储-使用NSUserDefaults 两个类介绍: NSUserDefaults适合存储轻量级的本地数据,比如要保存一个登陆界面的数据,用户名.密码之类的,个人觉得使用NSUserDefault ...

  4. 数据存储-CoreData总结

    CoreData /*英译  Entity:实体 Attributes:属性 binary:二进制 persistent:持续化 coordinator:协调者 meging:合并 configura ...

  5. Swift—Cocoa Touch设计模式-备

    目标(Target)与动作(Action)是iOS和OS X应用开发的中事件处理机制.   问题提出 如图所示是一个ButtonLabelSample案例设计原型图,其中包含一个标签和一个按钮,当点击 ...

  6. ios中常见数据存储方式以及SQLite常用的语句

    在iOS中,根据不同的需求对应的有多种数据存储方式: 1.NSUserdefaults  将数据存储到沙盒中(library),方便易用,但是只能存储系统提供的数据类型(plist),不能存储自定义的 ...

  7. C 标识符, 数据存储形式(原码,反码,补码)

    一.  标识符 第一个字母必须是英文字母或下划线 二. 数据存储形式(补码存储) 最高位是符号位 ---- 0表示整数 ; 1 表示负数 1. 正数:原码 = 反码 = 补码 例子 : (10) 原码 ...

  8. 《从零开始学Swift》学习笔记(Day 63)——Cocoa Touch设计模式及应用之单例模式

    原创文章,欢迎转载.转载请注明:关东升的博客 什么是设计模式.设计模式是在特定场景下对特定问题的解决方案,这些解决方案是经过反复论证和测试总结出来的.实际上,除了软件设计,设计模式也被广泛应用于其他领 ...

  9. 《从零開始学Swift》学习笔记(Day 63)——Cocoa Touch设计模式及应用之单例模式

    原创文章,欢迎转载.转载请注明:关东升的博客 什么是设计模式.设计模式是在特定场景下对特定问题的解决方式.这些解决方式是经过重复论证和測试总结出来的. 实际上.除了软件设计,设计模式也被广泛应用于其它 ...

随机推荐

  1. Mysql5.7的gtid主从半同步复制和组复制

    (一)gtid主从半同步复制 一.半同步复制原理 mysql默认的复制是异步的,主库在执行完客户端提交的事务后会立即将结果返回给客户端,并不关心从库是否已经接收并处理,这样就会有一个问题,主库如果cr ...

  2. PyalgoTrade 技术组合计算(四)

    可以各种技术可以组合起来.它们被建模为DataSeries.例如,在收盘价之上获得RSI以上的计算SMA,是非常简单的: from pyalgotrade import strategy from p ...

  3. mysql下,保存时间时具体时间丢失,只保存了日期的问题

    将日志信息记入数据库时增加了一个时间字段,发现存入数据库时只保留了日期,而没有时分秒信息. 我这边环境是(SRPINGMVC+Mybatis,mysql版本5.6.28以上),java层使用类型为ja ...

  4. It is the courage

    It is the reality that a society which becomes lower and becomes weak.Believe it or not,I think it i ...

  5. POJ3177 Redundant Paths【tarjan边双联通分量】

    LINK 题目大意 给你一个有重边的无向图图,问你最少连接多少条边可以使得整个图双联通 思路 就是个边双的模板 注意判重边的时候只对父亲节点需要考虑 你就dfs的时候记录一下出现了多少条连向父亲的边就 ...

  6. windows7下安装python环境和django

    1.安装python 1.1.首先访问http://www.python.org/download/去下载最新的python版本. 根据计算机位数选择对应的版本比如我的机器是64位的,我就下载这个安装 ...

  7. zipkin:HttpClient和struts

    因为要和老系统集成zipkin,意外的发现老系统使用的httpClient来发送信息.zipkin的官方demo可都是retstTemplate啊!有的搞头. 在看Demo的时候意外的发现其实其实2. ...

  8. python 简明教程

    第一个源程序 #!/usr/bin/python# Filename : helloworld.pyprint 'Hello world' 执行: $ python helloworld.py 或者  ...

  9. 黄聪:[C#]如何获取变量的名字,不是值,是名称。返回名字的字符串

    找了好久,最后在国外的论坛找到了解决办法,直接贴代码吧. 方法一: public static class MemberInfoGetting { public static string GetMe ...

  10. 保持一个会话 添加 HTTP Cookie管理器

    在线程组中添加 http cookie manager即可 场景:登录后点击刷新简历