iOS NSKeyedArchiver和NSKeyedUnarchiver
2021/5/18 18:55:36
本文主要是介绍iOS NSKeyedArchiver和NSKeyedUnarchiver,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
NSKeyedArchiver
和NSKeyedUnarchiver
两个类把对象序列化和反序列化。
所有的序列化对象必须继承NSSecureCoding
,例如NSString
、NSArray
等
-(void) stringArchiver { NSData* data = [NSKeyedArchiver archivedDataWithRootObject:@"Hello World" requiringSecureCoding:YES error:nil]; [data writeToFile:self.dataPath options:0 error:nil]; } -(void) stringUnarchiver { NSData* data = [NSData dataWithContentsOfFile:self.dataPath options:0 error:nil]; NSString* str = [NSKeyedUnarchiver unarchivedObjectOfClass:[NSString class] fromData:data error:nil]; NSLog(@"%@", str); }
自定义序列化对象Person
同样需要继承NSSecureCoding
,并实现initWithCoder:
、encodeWithCoder:
和supportsSecureCoding
方法
// Person.h @interface Person : NSObject<NSSecureCoding> @property (nonatomic, copy) NSString* name; @property (nonatomic, assign) NSInteger age; @end // Person.m @implementation Person - (instancetype)initWithCoder:(NSCoder *)aDecoder { self = [super init]; if (self) { self.name = [aDecoder decodeObjectForKey:@"name"]; self.age = [aDecoder decodeIntegerForKey:@"age"]; } return self; } - (void)encodeWithCoder:(NSCoder *)aEncoder { [aEncoder encodeObject:self.name forKey:@"name"]; [aEncoder encodeInteger:self.age forKey:@"age"]; } + (BOOL)supportsSecureCoding { return YES; } - (NSString *)description { return [NSString stringWithFormat:@"%@ - %ld", self.name, self.age]; } @end -(void) objectArchiver { Person* person = [[Person alloc] init]; person.name = @"Jack"; person.age = 18; NSData* data = [NSKeyedArchiver archivedDataWithRootObject:person requiringSecureCoding:YES error:nil]; [data writeToFile:self.dataPath options:0 error:nil]; } -(void) objectUnarchiver { NSData* data = [NSData dataWithContentsOfFile:self.dataPath options:0 error:nil]; Person* person = [NSKeyedUnarchiver unarchivedObjectOfClass:[Person class] fromData:data error:nil]; NSLog(@"%@", person); }
这篇关于iOS NSKeyedArchiver和NSKeyedUnarchiver的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-14Fetch / Axios学习:入门教程与实战指南
- 2024-11-14Typescript 类型课程入门教程
- 2024-11-14Fetch / Axios课程:初学者必看的网络请求教程
- 2024-11-14Styled-components课程:初学者指南
- 2024-11-13pre-commit 自动化测试课程:入门教程与实践指南
- 2024-11-13什么是AIGC?如何使用AIGC技术辅助办公?
- 2024-11-13Slicm 框架怎么进行用户认证?-icode9专业技术文章分享
- 2024-11-13在查询时将 map_coord 列的值转换为字符串有哪些方法?-icode9专业技术文章分享
- 2024-11-13如何将微信地区改成自定义文案?-icode9专业技术文章分享
- 2024-11-13DNS 缓存存在问题有哪些症状和解决方法?-icode9专业技术文章分享