ios之归档demo
2024-09-01 08:14:13
ios对自定义对象的归档。首先需要实现NSCoding与NSCopying接口
#import <Foundation/Foundation.h>
@interface Person : NSObject<NSCoding, NSCopying>
@property (copy,nonatomic)NSString *name;
@property(assign,nonatomic)NSInteger age;
@end
需要重写接口的3个方法
#import "Person.h" @implementation Person - (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:_name forKey:@"name"];
[aCoder encodeInteger:_age forKey:@"age"];
} - (id)initWithCoder:(NSCoder *)aDecoder {
if (self = [super init]) {
_name = [aDecoder decodeObjectForKey:@"name"];
_age =[aDecoder decodeIntegerForKey:@"age"];
}
return self;
} //#pragma mark NSCoping
- (id)copyWithZone:(NSZone *)zone {
Person *copy = [[[self class] allocWithZone:zone] init];
copy.name = [self.name copyWithZone:zone];
copy.age = self.age;
return copy;
}
//////////////////////////////////////////
归档的两种方法:
(1)使用NSUserDefaults
// 保存
Person *person = [[Person alloc] init];
person.name = _text.text;
person.age = (NSInteger)[_age text]; NSData *data = [NSKeyedArchiver archivedDataWithRootObject:person];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:@"person"]; // 读取
NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:@"person"];
NSArray *books = [NSKeyedUnarchiver unarchiveObjectWithData:data];
(2)使用写文件
// 保存文件目录
-(NSString*) appStorgeLocation{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory=[paths objectAtIndex:];//Documents目录
return [documentsDirectory stringByAppendingPathComponent:@"lee0000"];
} // 归档
Person *person = [[Person alloc] init];
person.name = _text.text;
person.age = (NSInteger)[_age text]; NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:person forKey:@"kArchivingDataKey"]; //archivingDate的encodeWithCoder方法被调用
[archiver finishEncoding];
//写入文件
[data writeToFile:[self appStorgeLocation] atomically:YES]; // 读取
NSData *data = [[NSMutableData alloc] initWithContentsOfFile:[self appStorgeLocation]];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data]; //获得类
Person *archivingData = [unarchiver decodeObjectForKey:@"kArchivingDataKey"];// initWithCoder方法被调用
[unarchiver finishDecoding];
最新文章
- 搭建个人wordpress博客(小白教程)
- LintCode Implement Queue by Two Stacks
- 游戏AI框架
- NSJSONSerialization
- easyUI中tree的简单使用
- 让sql语句不排序,按照in语句的顺序返回结果
- Java中Properties类的操作
- 亚信联创--java面试题目总结
- Android基本控件之ListView(一)
- Spket在Eclipse/MyEclipse下的安装和配置支持Ext(图文教程)
- Let&#39;s Encrypt+Apache+Tomcat实现免费HTTPS
- (Relax 水题1.2)POJ 1032 Parliament(将n分解成若干个互不相等的整数的和,并且是这些整数的乘积最大)
- php设计模式 1单例模式
- hdu-1800
- python2.7_1.14_编写一个简单的回显客户端/服务器应用
- [Swust OJ 179]--火柴棍(找规律)
- java文件上传Demo
- yum 安装Apache
- 用矩阵和待定系数法求数列的分析(复杂度log(n))
- 【文件】使用jacob将word转换成pdf格式