四种保存数据的方法
来源:互联网 发布:讯龙恢复软件注册码 编辑:程序博客网 时间:2024/06/05 09:24
一、<span style="color:#ff0000;">NSKeyedArchiver</span>:采用归档的形式保存数据,该数据对象必须得遵守NSCoding协议,并且该对象对应的类必须提供encodeWithCoder:和initWithCoder方法,前<span style="white-space:pre"></span> 一个方法告诉系统怎么对对象进行编码,后一个对象则是告诉系统如何对队形进行解码:例子如下
首先是Person类
#import <UIKit/UIKit.h>@interface Person : UIView<NSCoding>@property (nonatomic,assign) int age;@property (nonatomic,copy) NSString *name;@property (nonatomic,assign) float height;@end
#import "Person.h"@implementation Person#pragma mark 写入文件-(void)encodeWithCoder:(NSCoder *)aCoder{ [super encodeWithCoder:aCoder];//-----------不要忘记加这个 [aCoder encodeInt:self.age forKey:@"age"]; [aCoder encodeObject:self.name forKey:@"name"]; [aCoder encodeFloat:self.height forKey:@"height"];}#pragma mark 从文件中读取-(id)initWithCoder:(NSCoder *)aDecoder{ self = [super initWithCoder:aDecoder];//-----不要忘记加这个 self.age = [aDecoder decodeIntForKey:@"age"]; self.name = [aDecoder decodeObjectForKey:@"name"]; self.height = [aDecoder decodeFloatForKey:@"height"]; return self;}-(NSString *)description{ return [NSString stringWithFormat:@"name = %@,age = %d,height = %f",self.name,self.age,self.height];}@end
然后是ViewController
#import "ViewController.h"#import "Person.h"#define PERSON @"person1"@implementation ViewController-(void)viewDidLoad{ [super viewDidLoad]; [self createPerson]; [self readPerson];}-(void)createPerson{ Person *p = [[Person alloc]init]; p.age = 20; p.name = @"Rio"; p.height = 1.75; //获得Document路径 NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject]; NSString *path = [documents stringByAppendingPathComponent:PERSON]; [NSKeyedArchiver archiveRootObject:p toFile:path];}-(void)readPerson{ NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject]; NSString *path = [documents stringByAppendingPathComponent:PERSON]; Person *p = [NSKeyedUnarchiver unarchiveObjectWithFile:path]; NSLog(@"person:%@",p);}@end
</pre><pre name="code" class="objc">
二、NSUserDefaults:用来保存应用程序设置和属性以及用户保存的数据,用户再次打开应用程序之后这些数据仍然存在。可以存储的类型包括:NSData、NSDate、NSString、NSNumber、NSArray、NSDictionary。如要存储其他类型数据,在需要转换为前面的类型,才能用NSUserDefaults存储,具体实现方法在下面
0 0
- Android四种保存数据的方法
- Android 保存数据的四种方法
- 四种保存数据的方法
- ios常见的四种保存数据方法
- IOS 保存数据的四中方法
- ios 数据本地保存 四种方法
- IOS 四种保存数据的方式!
- IOS 四种保存数据的方式
- IOS 四种保存数据的方式
- IOS 四种保存数据的方式
- 四种保存数据的方式!
- IOS 四种保存数据的方式
- IOS 四种保存数据的方式
- iOS 四种保存数据的方式
- IOS 保存数据的四种方式
- IOS 四种保存数据的方式
- IOS 四种保存数据的方式!
- IOS 四种保存数据的方式
- VM虚拟机网络设置
- 下拉框实现两列或多列(webbuilder)
- Pascal's Triangle II
- PHPMyadmin 配置文件详解(配置)
- 实现Android支付宝声波支付时的波纹视图
- 四种保存数据的方法
- 解决方法:An error occurred on the server when processing the URL. Please contact the system administrato
- 微信公众平台开发教程第23篇-SAE不支持XStream框架的解决方案
- StartSSL——服务器配置https
- [C++]LeetCode: 80 Find Minimum in Rotated Sorted Array
- 聚类算法优秀博客链接
- web项目中读取web-inf下的properties文件
- c# sharp 中委托做参数的一个应用
- PHP中“简单工厂模式”实例讲解