要归档的类型,声明部分 .h
@interface AppList : NSObject
{
NSInteger app_id; //应用ID (10010)
NSString *name;
}
@property(readwrite) NSInteger app_id;
@property(copy,nonatomic) NSString *name;
-(void)encodeWithCoder:(NSCoder *)aCoder;
-(id)initWithCoder:(NSCoder *)aDecoder;
-(id)copyWithZone:(NSZone *)zone;
//实现部分 .m
@implementation AppList
@synthesize app_id,name;
-(void)setAppList:(NSDictionary *)dic
{
[self
setApp_id:[dic
objectForKey:@"app_id"]];
[self setName:[dic objectForKey:@"name"]];
}
-(id)initWithCoder:(NSCoder *)decoder//解码
{
if(self=[super init])
{
self.app_id=[decoder decodeIntForKey:@"app_id"];
self.name=[decoder decodeObjectForKey:@"name"];
}
return self;
}
-(void)encodeWithCoder:(NSCoder *)coder//编码
{
[coder encodeInt:app_id forKey:@"app_id"];
[coder encodeObject:name forKey:@"name"];
}
-(id)copyWithZone:(NSZone*)zone
{
AppList *copy=[[AppList allocWithZone:zone] init];
copy.app_id=self.app_id;
copy.name=[[self.name copyWithZone:zone] autorelease];
return copy;
}
-(void)dealloc
{
[name release];
[super dealloc];
}
//具体归档解档操作
NSMutableData *codingData = [[NSMutableData alloc]init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:codingData];
[archiver encodeObject:dataArray forKey:key];
[archiver finishEncoding];
BOOL result = [codingData writeToFile:filepathatomically:YES];
[archiver release];
[codingData release];
return result;
NSData *codingData = [[NSData alloc]initWithContentsOfFile:filePath];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiveralloc] initForReadingWithData:codingData];
NSMutableArray *data = [unarchiverdecodeObjectForKey:key];
[unarchiver finishDecoding];
[unarchiver release];
[codingData release];
return data;