Differences with archiveRootObject:toFile: and writeToFile:
Asked Answered
V

1

9

Recently, I'm learning about NSKeyedArchiver and NSKeyedUnarchiver. I found that there are three ways to archive an array and I'm trying to figure out the differences.

1.Using archiveRootObject:toFile:

    [NSKeyedArchiver archiveRootObject:testArray toFile:filePath];

2.Get data from archivedDataWithRootObject: and write it to file

    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:testArray];
    [data writeToFile:filePath atomically:YES];

3.Using encodeObject: to get data

    NSMutableData *data = [NSMutableData data];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    [archiver encodeObject:testArray forKey:@"testArray"];
    [archiver finishEncoding];
    [data writeToFile:path atomically:YES];

After testing, I found that all ways above work fine and write same content to file.

Q1: What's the differences with all the ways above?

Q2: Can I use NSData in the 3rd way?

Vertigo answered 18/4, 2013 at 7:42 Comment(0)
I
5

The first one doesn't give you a choice of what to do with the data. It will go to a file. I use the second way to, for example, send data across a network connection. It is more flexible. The 3rd way does the same thing except that you can put single objects into it. I'm not sure it will work with an array as it stands, but it might. It is even more flexible so you don't need to have an array or dictionary ready for it.

That's pretty much it. It is all about convenience vs flexibility.

Inerrable answered 18/4, 2013 at 7:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.