Question

Just getting started learning iOS and I've got a really basic question: What's the correct way to archive/unarchive a whole collection of objects?

I understand that you first need to implement the NSCoder protocol on the class. Assuming I've got a class that I can archive and unarchive correctly, I've been working through an example that looks like this:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *docsDir = [paths objectAtIndex:0];
NSString *archivePath = [docsDir stringByAppendingPathComponent:@"thing.model"];
Thing *thing = [[Thing alloc] init];
[NSKeyedArchiver archiveRootObject:thing toFile:archivePath];

Now, this is just saving one Thing as the file thing.model, correct?

So, if my app has many "things" and I want to archive them all, how do you approach that?

More specifically (in case some context helps), I'm developing an app that is backed by a web service, and I want to be able to create/edit records on the app, keep them saved to disk, and periodically sync the objects I've saved locally with the web service.

Thanks!

Était-ce utile?

La solution

The collection classes conform to NSCoding. So if you have an NSArray of Thing objects, just archive/unarchive the array.

Autres conseils

So, if my app has many "things" and I want to archive them all, how do you approach that?

If you want to save each of those things individually, use -encodeObject:forKey: to add an object (and the key that you'll use to retrieve it later) to the archive.

As rmaddy pointed out, if all the things are in a collection, you can just archive the collection as a single object. Again, you can do that using -encodeObject:forKey:, or if the collection is to be the only thing in the archive you can do it the way you're doing it above, using archiveRootObject:toFile:.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top