对象的序列化与反序列化
首先创建一个对象做数据源
.h头文件 遵循NSSecureCoding协议
@interface ABoss : NSObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, assign) CGFloat money;
@property (nonatomic, strong) NSString *company;
+(void)saveObj:(ABoss *)boss withFileName:(NSString *)fileName;
+(ABoss *)readObjWithFileName:(NSString *)fileName;
@end
.m文件 必须实现的方法有:
-(void)encodeWithCoder:(NSCoder *)aCoder
-(instancetype)initWithCoder:(NSCoder *)aDecoder
+(BOOL)supportsSecureCoding
@implementation ABoss
-(void)encodeWithCoder:(NSCoder *)aCoder{
NSLog(@"encode");
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeFloat:self.money forKey:@"money"];
[aCoder encodeObject:self.company forKey:@"company"];
}
-(instancetype)initWithCoder:(NSCoder *)aDecoder{
NSLog(@"decodera");
if (self==[super init]) {
self.name=[aDecoder decodeObjectForKey:@"name"];
self.money=[aDecoder decodeFloatForKey:@"money"];
self.company=[aDecoder decodeObjectForKey:@"company"];
NSLog(@"decoderb");
}
NSLog(@"decodec");
return self;
}
/**
支持NSSecureCoding协议 必须支持
@return 必须支持
*/
+(BOOL)supportsSecureCoding{
return YES;
}
/**
序列化该类的对象
@param boss ABoss 实例
@param fileName 保存的文件名
*/
+(void)saveObj:(ABoss *)boss withFileName:(NSString *)fileName{
NSString *filePath=[NSHomeDirectory() stringByAppendingPathComponent:fileName];
{
NSData *data=[NSKeyedArchiver archivedDataWithRootObject:boss requiringSecureCoding:YES error:nil];
[data writeToFile:filePath atomically:YES];
}
}
/**
反序列化该类的对象
@param fileName 需反序列化的文件
@return return ABoss 实例
*/
+(ABoss *)readObjWithFileName:(NSString *)fileName{
NSString *filePath=[NSHomeDirectory() stringByAppendingPathComponent:fileName];
NSData *oldData=[NSData dataWithContentsOfFile:filePath];
NSError *error;
return [NSKeyedUnarchiver unarchivedObjectOfClass:[ABoss class] fromData:oldData error:&error];
}
@end
既然数据已做好,那么可以直接使用了
-(void)saveAData{
ABoss *boss=[[ABoss alloc] init];
boss.name=@"chen bai qiang";
boss.money=6658654869.00;
boss.company=@"tianxiadiyi";
[ABoss saveObj:boss withFileName:@"abboss.archive"];
}
-(void)readData{
ABoss *boss=[ABoss readObjWithFileName:@"abboss.archive"];
NSLog(@"boss information's name:%@,money:%.2f,company:%@",boss.name,boss.money,boss.company);
}
运行 打印如下
encode
decodera
decoderb
decodec
boss information's name:chen bai qiang,money:6658654720.00,company:tianxiadiyi
上面的对象序列化也可以写到pch文件
#ifndef PrefixHeader_pch
#define PrefixHeader_pch
#import
#define SERIALIZER_CODER_DECODER() \
\
- (id)initWithCoder:(NSCoder *)coder \
{ \
Class cls = [self class]; \
while (cls != [NSObject class]) { \
/*判断是自身类还是父类*/ \
BOOL bIsSelfClass = (cls == [self class]); \
unsigned int iVarCount = 0; \
unsigned int propVarCount = 0; \
unsigned int sharedVarCount = 0; \
Ivar *ivarList = bIsSelfClass ? class_copyIvarList([cls class], &iVarCount) : NULL;/*变量列表,含属性以及私有变量*/ \
objc_property_t *propList = bIsSelfClass ? NULL : class_copyPropertyList(cls, &propVarCount);/*属性列表*/ \
sharedVarCount = bIsSelfClass ? iVarCount : propVarCount; \
\
for (int i = 0; i < sharedVarCount; i++) { \
const char *varName = bIsSelfClass ? ivar_getName(*(ivarList + i)) : property_getName(*(propList + i)); \
NSString *key = [NSString stringWithUTF8String:varName]; \
id varValue = [coder decodeObjectForKey:key]; \
NSArray *filters = @[@"superclass", @"description", @"debugDescription", @"hash"]; \
if (varValue && [filters containsObject:key] == NO) { \
[self setValue:varValue forKey:key]; \
} \
} \
free(ivarList); \
free(propList); \
cls = class_getSuperclass(cls); \
} \
return self; \
} \
\
- (void)encodeWithCoder:(NSCoder *)coder \
{ \
Class cls = [self class]; \
while (cls != [NSObject class]) { \
/*判断是自身类还是父类*/ \
BOOL bIsSelfClass = (cls == [self class]); \
unsigned int iVarCount = 0; \
unsigned int propVarCount = 0; \
unsigned int sharedVarCount = 0; \
Ivar *ivarList = bIsSelfClass ? class_copyIvarList([cls class], &iVarCount) : NULL;/*变量列表,含属性以及私有变量*/ \
objc_property_t *propList = bIsSelfClass ? NULL : class_copyPropertyList(cls, &propVarCount);/*属性列表*/ \
sharedVarCount = bIsSelfClass ? iVarCount : propVarCount; \
\
for (int i = 0; i < sharedVarCount; i++) { \
const char *varName = bIsSelfClass ? ivar_getName(*(ivarList + i)) : property_getName(*(propList + i)); \
NSString *key = [NSString stringWithUTF8String:varName]; \
/*valueForKey只能获取本类所有变量以及所有层级父类的属性,不包含任何父类的私有变量(会崩溃)*/ \
id varValue = [self valueForKey:key]; \
NSArray *filters = @[@"superclass", @"description", @"debugDescription", @"hash"]; \
if (varValue && [filters containsObject:key] == NO) { \
[coder encodeObject:varValue forKey:key]; \
} \
} \
free(ivarList); \
free(propList); \
cls = class_getSuperclass(cls); \
} \
} \
+(BOOL)supportsSecureCoding{ \
return YES; \
}
#endif /* PrefixHeader_pch */
.m文件
然后在需要实现的文件加 SERIALIZER_CODER_DECODER()
@implementation ABoss
SERIALIZER_CODER_DECODER()
/**
序列化该类的对象
@param boss ABoss 实例
@param fileName 保存的文件名
*/
+(void)saveObj:(ABoss *)boss withFileName:(NSString *)fileName{
NSString *filePath=[NSHomeDirectory() stringByAppendingPathComponent:fileName];
{
NSData *data=[NSKeyedArchiver archivedDataWithRootObject:boss requiringSecureCoding:YES error:nil];
[data writeToFile:filePath atomically:YES];
}
}
/**
反序列化该类的对象
@param fileName 需反序列化的文件
@return return ABoss 实例
*/
+(ABoss *)readObjWithFileName:(NSString *)fileName{
NSString *filePath=[NSHomeDirectory() stringByAppendingPathComponent:fileName];
NSData *oldData=[NSData dataWithContentsOfFile:filePath];
NSError *error;
return [NSKeyedUnarchiver unarchivedObjectOfClass:[ABoss class] fromData:oldData error:&error];
}
@end
Json序列化与反序列化
-(void)lib{
NSDictionary *sender=@{@"a":@"11",
@"b":@"22",
@"c":@"33"
};
NSLog(@"原数据:%@",sender);
[self jsonSerializationWithDict:sender];
}
-(void)jsonSerializationWithDict:(id)sender{
NSError *error;
NSData *data=[NSJSONSerialization dataWithJSONObject:sender options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"JSON序列化:%@",jsonString);
[self jsonReverseSerializationWithDict:jsonString];
}
-(void)jsonReverseSerializationWithJsonString:(NSString *)sender{
NSData *data=[sender dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
NSLog(@"JSON反序列化:%@",dict);
}
运算结果如下
原数据:{
a = 11;
b = 22;
c = 33;
}
JSON序列化:{
"a" : "11",
"b" : "22",
"c" : "33"
}
JSON反序列化:{
a = 11;
b = 22;
c = 33;
}