1、NSKeyedArchiver、NSKeyedUnArchiver
1)、archiveRootObject:toFile 归档对象到这个路径文件
2)、unarchiveObjectWithFile:从这个路径文件把对象进行恢复
对象归档这里我们可以理解Android里面的序列化,就是把对象保存到文件持久化,Android里面进行持久化的必须实现Serializable和Parcelable,然后IOS里面持久化必须实现NSCodeing协议,IOS进行持久化操作一般需要NSKeyedArchiver实现。
2、NSCodeing协议
1)、initWithCoder:该方法恢复对象
2)、encodeWithCoder:归档该对象
3、测试Demo(把Dictionary和普通对象进行对象归档)
IApple.h
#import <Foundation/Foundation.h>
#ifndef IApple_h
#define IApple_h
@interface IApple : NSObject <NSCoding>
@property (nonatomic, copy) NSString *color;
@property (nonatomic, assign) double weight;
@property (nonatomic, assign) int size;
-(id)initWithColor:(NSString *) color weight:(double) weight size:(int) size;
@end
#endif /* IApple_h */
IApple.m
#import "IApple.h"
#import <Foundation/Foundation.h>
@implementation IApple
@synthesize color = _color;
@synthesize weight = _weight;
@synthesize size = _size;
-(id)initWithColor:(NSString *) color weight:(double) weight size:(int) size
{
if (self = [super init])
{
self.color = color;
self.weight = weight;
self.size = size;
}
return self;
}
-(NSString *)description
{
return [NSString stringWithFormat:@"<IApple [color = %@, weight = %g, _size = %d]>", self.color, self.weight, self.size];
}
-(void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:_color forKey:@"color"];
[aCoder encodeDouble:_weight forKey:@"weight"];
[aCoder encodeInt:_size forKey:@"size"];
}
-(id) initWithCoder:(NSCoder *)aDecoder
{
_color = [aDecoder decodeObjectForKey:@"color"];
_weight = [aDecoder decodeDoubleForKey:@"weight"];
_size = [aDecoder decodeIntForKey:@"size"];
return self;
IOS学习笔记二十三对象归档(NSKeyedArchiver、NSKeyedUnArchiver、NSCodeing)
最新推荐文章于 2025-12-27 00:14:52 发布
本文介绍了iOS中对象持久化的方法,主要讲解了NSKeyedArchiver和NSCoding协议的使用。通过archiveRootObject:toFile:和unarchiveObjectWithFile:进行对象的存档和恢复。同时,详细阐述了NSCoding协议的initWithCoder:和encodeWithCoder:方法。并提供了一个IApple对象的归档和解档示例代码,展示了如何将Dictionary和普通对象进行对象归档。

1946

被折叠的 条评论
为什么被折叠?



