用NSCoding协议完成“编码/解码”操作-Object-C
原文:http://blog.sina.com.cn/s/blog_7b9d64af01019kk5.html
Object-C中我们可以对 NSDate, NSNumber, NSString, NSArray, or NSDictionary对象进行“编码/解码”的操作。
- (void)encodeWithCoder:(NSCoder *)aCoder;
- (id)initWithCoder:(NSCoder *)aDecoder;
@interface AddressCard : NSObject<NSCopying,NSCoding>
#pragma mark- NSCoding
- (void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:self.name forKey:@"AddressCard_name"];
[aCoder encodeObject:self.email forKey:@"AddressCard_email"];
[aCoder encodeInt32:self.salary forKey:@"AddressCard_salary"];
}
- (id)initWithCoder:(NSCoder *)aDecoder{
_name=[[aDecoder decodeObjectForKey:@"AddressCard_name"] retain];
_email=[[aDecoder decodeObjectForKey:@"AddressCard_email"] retain];
_salary=[aDecoder decodeInt32ForKey:@"AddressCard_salary"];
return self;
}
NSString *filePhyName=[filePath stringByAppendingPathComponent:@"ObjectFile"];
BOOL isSuccess=NO;
isSuccess= [NSKeyedArchiver archiveRootObject:objArray toFile:filePhyName];
if (isSuccess) {
NSLog(@"Success");
}else{
NSLog(@"False");
}
// 反归档
NSMutableArray *myObj=[NSKeyedUnarchiver unarchiveObjectWithFile:filePhyName];
for (AddressCard *theCard in myObj) {
[theCard print];
}
使用NSSecureCoding协议进行对象编解码
原文:http://blog.jobbole.com/67655/