哦,是的!我得到了它。在以下人员/帖子的大力帮助下...
Gave me the idea to use associatedObjects
Explanation of associatedObjects
and method swizzling
在 UIColor 上创建一个类别。使用关联对象在 UIColor 实例中设置对图案图像的引用(有点像动态属性),不要忘记导入 <objc/runtime.h>。在创建 UIColor color = [UIColor colorWithPatternImage:selectedImage] 时,还要在颜色 [color setAssociatedObject:selectedImage] 上设置关联对象。
然后实现类中自定义的encodeWithCoder和initWithCoder方法,对UIImage进行序列化。
最后在 main.m 文件中进行一些方法调配,以便您可以从 UIColor 类别中调用原始的 UIColor encodeWithCoder 和 initWithCoder 方法。然后你甚至不需要为 Core Data 编写你自己的 Value Transformer,因为 UIColor 实现了 NSCoding 协议。下面的代码...
UIColor+patternArchive
#import "UIColor+patternArchive.h"
#import <objc/runtime.h>
@implementation UIColor (UIColor_patternArchive)
static char STRING_KEY; // global 0 initialization is fine here, no
// need to change it since the value of the
// variable is not used, just the address
- (UIImage*)associatedObject
{
return objc_getAssociatedObject(self,&STRING_KEY);
}
- (void)setAssociatedObject:(UIImage*)newObject
{
objc_setAssociatedObject(self,&STRING_KEY,newObject,OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (void)encodeWithCoderAssociatedObject:(NSCoder *)aCoder
{
if (CGColorSpaceGetModel(CGColorGetColorSpace(self.CGColor))==kCGColorSpaceModelPattern)
{
UIImage *i = [self associatedObject];
NSData *imageData = UIImagePNGRepresentation(i);
[aCoder encodeObject:imageData forKey:@"associatedObjectKey"];
self = [UIColor clearColor];
} else {
// Call default implementation, Swizzled
[self encodeWithCoderAssociatedObject:aCoder];
}
}
- (id)initWithCoderAssociatedObject:(NSCoder *)aDecoder
{
if([aDecoder containsValueForKey:@"associatedObjectKey"])
{
NSData *imageData = [aDecoder decodeObjectForKey:@"associatedObjectKey"];
UIImage *i = [UIImage imageWithData:imageData];
self = [[UIColor colorWithPatternImage:i] retain];
[self setAssociatedObject:i];
return self;
}
else
{
// Call default implementation, Swizzled
return [self initWithCoderAssociatedObject:aDecoder];
}
}
main.m
#import <UIKit/UIKit.h>
#import <objc/runtime.h>
#import "UIColor+patternArchive.h"
int main(int argc, char *argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// Swizzle UIColor encodeWithCoder:
Method encodeWithCoderAssociatedObject = class_getInstanceMethod([UIColor class], @selector(encodeWithCoderAssociatedObject:));
Method encodeWithCoder = class_getInstanceMethod([UIColor class], @selector(encodeWithCoder:));
method_exchangeImplementations(encodeWithCoder, encodeWithCoderAssociatedObject);
// Swizzle UIColor initWithCoder:
Method initWithCoderAssociatedObject = class_getInstanceMethod([UIColor class], @selector(initWithCoderAssociatedObject:));
Method initWithCoder = class_getInstanceMethod([UIColor class], @selector(initWithCoder:));
method_exchangeImplementations(initWithCoder, initWithCoderAssociatedObject);
int retVal = UIApplicationMain(argc, argv, nil, nil);
[pool release];
return retVal;
}