保存添加到类扩展的额外数据

时间:2012-05-02 10:14:09

标签: iphone objective-c ios nsarray nskeyedarchiver

我创建了一个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;

}

1 个答案:

答案 0 :(得分:3)

我认为您无法通过相关对象API添加属性,因为UIImage的{​​{1}}和encodeWithCoder:不知道您的属性在那里。

如果您可以通过继承initWithCoder:来创建自定义MyUiImage,则可以覆盖类的UIImageencodeWithCoder:,并对您的属性进行编码/解码以及initWithCoder:个。