您的位置:首页 > 其它

归档(archive)文件(二)

2015-12-22 15:40 218 查看
http://blog.sina.com.cn/s/blog_7b9d64af01019kw8.html

可以参见我的第一篇关于归档的说明。

归档(archive)文件(一)

考虑如下情况:

1.我们有很多不同的对象需要归档,并且对象之间可能相差很大,每次进行归档麻烦,效率也不高。

2.被归档的对象不确定有多少个。

3.希望将不同对象归档到一个文件中,易于操作。

所以,如果我们能够全部将需要归档的对象首先存放在一个空间中,然后,一次性归档。这样做,那就方便多了!

这就是今天的主角登场!使用NSData和NSMutableData来进行归档!

由于,前面篇幅的说明,只需要贴代码了:

 

    NSMutableData *dataArear=[NSMutableData data];

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

    [archiver encodeObject:objArray forKey:@"AddressCard_Array"];

    [archiver encodeObject:card1 forKey:@"AddressCard_SingleObj"];

    [archiver finishEncoding];

    [archiver release];// 注意释放

    BOOL isOk=[dataArear writeToFile:filePhyName atomically:YES];

    if (isOk) {

        NSLog(@"Success!");

    }else{

        NSLog(@"False!");

    }

    

   

    NSMutableData *theData=[NSMutableData dataWithContentsOfFile:filePhyName];

    NSKeyedUnarchiver *unarchiver=[[NSKeyedUnarchiver alloc] initForReadingWithData:theData];

    NSMutableArray *cardArray=[unarchiver decodeObjectForKey:@"AddressCard_Array"];

    AddressCard *theCard=[unarchiver decodeObjectForKey:@"AddressCard_SingleObj"];

    [unarchiver finishDecoding];

    [unarchiver release];// 注意释放

    for (AddressCard *theCard in cardArray) {

        [theCard print];

    }

    [theCard print];

希望对您有所帮助!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: