Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the relationship between NSCoding and NSData?

I'm new to iOS programming and I've just learned some basics about saving/loading objects. In my book there is an example of saving an image to file:

NSData *data = UIImageJPEGRepresentation(someImage, 0.5);
[data writeToFile:imagePath atomically:YES];

My book also has an example of saving an "essay" object to file (an "essay" object has a string for title and another string for author):

essay.m conforms to the <NSCoding> protocol:

- (void) encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self.essayTitle forKey:@"essayTitle"];
    [aCoder encodeObject:self.essayAuthor forKey:@"essayAuthor"];

}
- (instancetype) initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];
    if (self) {
        _essayTitle = [aDecoder decodeObjectForKey:@"essayTitle"];
        _essayAuthor = [aDecoder decodeObjectForKey:@"essayAuthor"];
    }
    return self;
}

in essayStore.m:

[NSKeyedArchiver archiveRootObject:self.myEssay toFile:somePath];

I have three questions:

  1. When should I use NSData to save objects to a file/files and when should I conform to the <NSCoding> protocol to save objects to a file/files?

  2. When should I save all objects to a single file and when should I save one file for each object?

  3. If my essay object has an image in it, how can I save it with the image?

Thanks!

like image 745
wz366 Avatar asked Nov 11 '22 10:11

wz366


1 Answers

1. NSCoding is a protocol and is one of the methods of saving data to files. The advantage is that you can store your objects as such if using this method.
NSData, as mentioned in the Apple class reference is typically used for data storage and are also useful in Distributed Objects applications, where data contained in data objects can be copied or moved between applications.

2. This depends on your need to save data. Its usually enough to store all objects in a single file, and these are usually the objects that represent a entity.

3. You may refer to the following tutorial:
- List item NSCoding Tutorial for iOS

EDIT:

If you want to know about encoding images, take a look at this stackoverflow answer.
Although encoding images is not an option I would prefer. Complex objects need to be converted to primitive data as mentioned by @Anoop Vaidya in the comments.

And yes, it is possible to encode objects of classes created by you. But you have to implement NSCoding protocol in them. the following link is an apt example of a two level encoding, as you asked for:

  • Archiving Objective-C Objects with NSCoding

Hope this helps!

like image 160
GoGreen Avatar answered Nov 15 '22 06:11

GoGreen