iOS开发中,我们可能需要将一些内存中的数据存储到本地中,以便下次进入程序的时候使用,这个时候我们就需要归档,其实,就是将一些对象进行编码保存到磁盘中,然后再使用的时候再对这些数据进行解码,然后使用。涉及到的类为NSKeyedArchiver和NSKeyedUnarchiver。下面我们来看一个例子,例如我们从服务器上取到了一些xml数据,然后经过解析之后,我们可能想要把解析出来的数据保存到硬盘中,这个时候,我们就得创建一个相对应的实体类来保存数据,这时候这个类就需要遵循NSCoding协议,并实现协议中的两个方法:
- (void)encodeWithCoder:(NSCoder *)aCoder;
- (id)initWithCoder:(NSCoder *)aDecoder;
#import <Foundation/Foundation.h>
@interface Info : NSObject<NSCoding>{
NSString *infoID;
NSString *infoName;
NSString *infoImage;
NSString *infoArtist;
}
@property(nonatomic,copy)NSString *infoID;
@property(nonatomic,copy)NSString *infoName;
@property(nonatomic,copy)NSString *infoImage;
@property(nonatomic,copy)NSString *infoArtist;
@end
#import "Info.h"
@implementation Info
@synthesize infoID,infoName,infoImage,infoArtist;
-(void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:infoID forKey:@"infoID"];
[aCoder encodeObject:infoName forKey:@"infoName"];
[aCoder encodeObject:infoImage forKey:@"infoImage"];
[aCoder encodeObject:infoArtist forKey:@"infoArtist"];
}
-(id)initWithCoder:(NSCoder *)aDecoder{
if (self=[super init]) {
self.infoID=[aDecoder decodeObjectForKey:@"infoID"];
self.infoName=[aDecoder decodeObjectForKey:@"infoName"];
self.infoImage=[aDecoder decodeObjectForKey:@"infoImage"];
self.infoArtist=[aDecoder decodeObjectForKey:@"infoArtist"];
}
return self;
}
@end
NSMutableData *archiveData=[NSMutableData data];
NSKeyedArchiver *archiver=[[NSKeyedArchiver alloc]initForWritingWithMutableData:archiveData];
[archiver encodeObject:infoArray forKey:@"pInfoArray"];
[archiver finishEncoding];
NSString *document=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath=[document stringByAppendingPathComponent:@"storeFile"];
[archiveData writeToFile:filePath atomically:YES];
而在需要使用这些数据的时候就可以:NSString *document=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *storeFile=[document stringByAppendingPathComponent:@"storeFile"];
if ([[NSFileManager defaultManager] fileExistsAtPath:storeFile]) {
NSData *data=[NSData dataWithContentsOfFile:storeFile];
if ([data length]>0) {
NSKeyedUnarchiver *Unarchiver=[[NSKeyedUnarchiver alloc] initForReadingWithData:data];
NSArray *array=[Unarchiver decodeObjectForKey:@"pInfoArray"];
[Unarchiver finishDecoding];
[Unarchiver release];
for (int i=0;i<[array count]; i++) { Info *tempInfo=[array objectAtIndex:i];
...
}
}
}