ios序列化

你于写数据需要本地存储时,即将你的数据写到硬盘上的时候,你就必须对他进行序列化,转换成二进制文件,从而便于在磁盘上的读写,同理在取出的时候必须将其在反序列化,这样才能将数据读出来,就好比加密和解密的过程。


NSUserDefaults只支持: NSString, NSNumber, NSDate, NSArray, NSDictionary.
如果把一个自定义的类存到一个NSArray里,然后再存到NSUserDefaults里也是不能成功的。
那怎么办呢?
让这个自定义类实现<NSCoding>协议中的- (id) initWithCoder: (NSCoder *)coder方法和- (void) encodeWithCoder: (NSCoder *)coder方法(obj-c的协议protocol就是java的接口interface,就是C++的纯虚函数),然后把该自定义的类对象编码到NSData中,再从NSUserDefaults中进行读取。

假设有这样一个简单的类对象

view plaincopy to clipboardprint?
@interface BusinessCard : NSObject <NSCoding>{  
    NSString *_firstName;  
    NSString *_lastName;  
}  
@property (nonatomic, retain) NSString *_firstName;  
@property (nonatomic, retain) NSString *_lastName;  
@end;  

@implementation BusinessCard  
@synthesize _firstName, _lastName;  
- (void)dealloc{  
    [_firstName release];  
    [_lastName release];  
    [super dealloc];  
}  
- (id) initWithCoder: (NSCoder *)coder  
{  
if (self = [super init])  
    {  
        self._firstName = [coder decodeObjectForKey:@"_firstName"];  
        self._lastName = [coder decodeObjectForKey:@"_lastName"];  
    }  
return self;  
}  
- (void) encodeWithCoder: (NSCoder *)coder  
{  
    [coder encodeObject:_firstName forKey:@"_firstName"];  
    [coder encodeObject:_lastName forKey:@"_lastName"];  

}  

@end
然后再存取时通过NSData做载体:
BusinessCard *bc = [[BusinessCard alloc] init];  
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];  
NSData *udObject = [NSKeyedArchiver archivedDataWithRootObject:bc];  
[ud setObject:udObject forKey:@"myBusinessCard"];  
[bc release];  
udObject = nil;  
udObject = [ud objectForKey:@"myBusinessCard"];  
bc = [NSKeyedUnarchiver unarchiveObjectWithData:udObject] ;  

你可能感兴趣的:(ios)