我创建了一个 UIImage 类,该类还包含应绘制图像的坐标数据:
#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);
}
到目前为止一切都很好。我有一个包含这些图像数组的类。该类称为 BookDoc,该数组称为插图。当我复制 BookDoc 的实例时,我复制了数组。我为每个图像定义的 originData 复制得很好。
但是,当我将这个新副本保存到文件时,我会丢失 originData。这是我的保存方法:
- (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;
}
我的问题是 - 如何确保保存每个图像的 originData?非常感谢。
更新:
好的,我已经在一个名为 UIImageExtra 的类中更改了 UIImage 的子类,并使其符合 NSCoding 如下:
- (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;
}
现在当我保存包含这些 UIImageExtra 实例的插图数组时,它不应该自动保存原始数据吗?我保存数组的代码如下所示:
- (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;
}