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:
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?When should I save all objects to a single file and when should I save one file for each object?
If my essay object has an image in it, how can I save it with the image?
Thanks!