I've created a UIImage class that also contains coordinate data of where the image should be drawn:
#import "UIImageExtras.h"
#import <objc/runtime.h>
@implementation UIImage (Extras)
static char UII_ORIGINDATA_KEY;
@dynamic originData;
- (void)setOriginData:(NSValue *)originData {
objc_setAssociatedObject(self, &UII_ORIGINDATA_KEY, originData, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (NSValue *)originData {
return (NSValue *)objc_getAssociatedObject(self, &UII_ORIGINDATA_KEY);
}
All good so far. I have a class containing an array of these such images. The class is called BookDoc and the array is called illustrations. When I copy an instance of BookDoc, I copy the array. The originData I have defined for each image copies fine.
However, when I then save this new copy to file, I lose the originData. This is my save method:
- (void)saveIllustrations {
if (_illustrations == nil) {
NSLog(@"Nil array");
return;
}
[self createDataPath];
NSString *illustrationsArrayPath = [_docPath stringByAppendingPathComponent:kIllustrationsFile];
BOOL result = [NSKeyedArchiver archiveRootObject:_illustrations toFile:illustrationsArrayPath];
if (!result)
NSLog(@"Failed to archive array");
//This is not saving the originData.
self.illustrations = nil;
}
My question is - how can I ensure that the originData for each image is saved? Many thanks.
UPDATE:
Ok, I've changed to subclassing UIImage in a class called UIImageExtra, and made it conform to NSCoding as follows:
- (void)encodeWithCoder:(NSCoder *)aCoder {
NSLog(@"Encoding origin data!");
[aCoder encodeObject:originData forKey:kOriginData];
[super encodeWithCoder:aCoder];
}
- (id)initWithCoder:(NSCoder *)aDecoder {
if (self = [super initWithCoder:(NSCoder *) aDecoder]) {
NSLog(@"Decoding origin data");
self.originData = [aDecoder decodeObjectForKey:kOriginData];
}
return self;
}
Now when I save the illustrations array containing these UIImageExtra instances, shouldn't it automatically save the origin data? My code for saving the array looks like this:
- (void)saveIllustrations {
if (_illustrations == nil) {
NSLog(@"Nil array");
return;
}
[self createDataPath];
NSString *illustrationsArrayPath = [_docPath stringByAppendingPathComponent:kIllustrationsFile];
BOOL result = [NSKeyedArchiver archiveRootObject:_illustrations toFile:illustrationsArrayPath];
if (!result)
NSLog(@"Failed to archive array");
//This is not saving the originData.
self.illustrations = nil;
}