initWithCoder 和 decodeWithCoder

来源:互联网 发布:编程里面绝对值的表示 编辑:程序博客网 时间:2024/06/06 20:17

编码:

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 = [fileManagerfileExistsAtPath: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 = [fileManagerfileExistsAtPath:path isDirectory:&isDir];

   if ( !(isDir ==YES && existed ==YES) ){

        [fileManager createDirectoryAtPath:pathwithIntermediateDirectories:YESattributes:nilerror:nil];

    }

    return [NSKeyedUnarchiverunarchiveObjectWithFile:path];

}