编码:
TestData *testData = [[TestDataalloc] init];
testData.testDate = [NSDatedate];
testData.testString =@"hello world";
[testDataarchiveSelf];
解码:
TestData *testData = [[TestDataalloc] init];
testData = [testDataunarchiveSelf];
具体实现
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [superinit];
if(self)
{
self.testString = [aDecoderdecodeObjectForKey:@"testString"];
self.testDate = [aDecoderdecodeObjectForKey:@"testDate"];
}
return self;
}
-(void)encodeWithCoder:(NSCoder *)aCoder{
[aCoderencodeObject:self.testStringforKey:@"testString"];
[aCoderencodeObject:self.testDateforKey:@"testDate"];
}
- (void)archiveSelf
{
NSFileManager *fileManager = [NSFileManagerdefaultManager];
NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *path = [[pathsobjectAtIndex:0]stringByAppendingPathComponent:@"test"];
BOOL isDir = NO;
BOOL existed = [fileManager fileExistsAtPath:path isDirectory:&isDir];
if ( !(isDir == YES && existed ==YES) ){
[fileManager createDirectoryAtPath:pathwithIntermediateDirectories:YESattributes:nilerror:nil];
}
NSString *fname = [pathstringByAppendingPathComponent:[NSStringstringWithFormat:@"test.dat"]];//todo 测试会不会覆盖
//归档
[NSKeyedArchiverarchiveRootObject:selftoFile:fname];
}
- (id)unarchiveSelf
{
NSFileManager *fileManager = [NSFileManagerdefaultManager];
NSArray *rootPath =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *path = [[[rootPathobjectAtIndex:0]stringByAppendingPathComponent:@"test"]stringByAppendingPathComponent:@"test.dat"];
BOOL isDir = NO;
BOOL existed = [fileManager fileExistsAtPath:path isDirectory:&isDir];
if ( !(isDir == YES && existed ==YES) ){
[fileManager createDirectoryAtPath:pathwithIntermediateDirectories:YESattributes:nilerror:nil];
}
return [NSKeyedUnarchiverunarchiveObjectWithFile:path];
}