iOS 解档归档

来源:互联网 发布:单片机产生脉冲信号 编辑:程序博客网 时间:2024/04/30 04:46

【归档步骤】

1.需要归档的数据结构中,任何对象都必须遵从归档协议NSCoding.实现相关方法

- (void)encodeWithCoder:(NSCoder *)aCoder;

- (id)initWithCoder:(NSCoder *)aDecoder;

2.使用KeyedAchiever进行归档


关于协议的实现

#pragma mark归档方法

-(void)encodeWithCoder:(NSCoder *)aCoder{

    [aCoderencodeObject:self.nameforKey:@"name"];

    [aCoderencodeObject:self.IDforKey:@"ID"];

    [aCoderencodeObject:[NSNumbernumberWithInt:self.age]forKey:@"age"];

}


#pragma mark解档方法

-(id)initWithCoder:(NSCoder *)aDecoder{

   if (self = [superinit]) {

       self.name = [aDecoderdecodeObjectForKey:@"name"];

       self.ID = [aDecoderdecodeObjectForKey:@"ID"];

       self.age = [[aDecoderdecodeObjectForKey:@"age"]intValue];

    }

   returnself;

}


//归档操作

NSMutableData *data = [[NSMutableData alloc] init];

NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];

[archiver encodeObject:school forKey:@"school"];

[archiver finishEncoding];

[data writeToFile:PATH atomically:YES];


【解归档步骤】

1.首先要确定你拥有同样的数据结构

2.使用KeyedUnAchiever进行解归档


//解档操作

NSData *data = [[NSDataalloc]initWithContentsOfFile:PATH];

NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiveralloc]initForReadingWithData:data];

School *school = [unarchiverdecodeObjectForKey:@"school"];

[unarchiverfinishDecoding];

[schoolshowStudents];


0 0
原创粉丝点击