我目前有一个存储数据的核心数据数据库,我也希望在其中存储一个NSColor,但它不接受NSColor作为对象。我的解决方案是将其作为字符串存储在数据库中,并在加载时将其读取到NSColor中。我该怎么做呢?
例如,如果我有一个像[NSColor redColor]这样的颜色,我如何将它存储在数据库中(作为字符串),然后检索它。这是一个基本的例子,最后它将是更复杂的RGB颜色。
谢谢。
发布于 2012-06-09 06:44:38
您应该考虑使用NSData作为容器,用于在核心数据中存储不支持的数据类型。要将NSColor作为NSData访问,您需要将属性标记为可转换,并创建可逆的NSValueTransformer类以将NSColor转换为NSData。
发布于 2012-06-09 07:25:53
我同意推荐使用NSData在核心数据存储中存储颜色的答案。也就是说,有时在字符串中存储颜色可能很有用,而且这样做并不困难。我建议在NSColor上创建一个类别:
@interface NSColor (NSString)
- (NSString*)stringRepresentation;
+ (NSColor*)colorFromString:(NSString*)string forColorSpace:(NSColorSpace*)colorSpace;
@end
@implementation NSColor (NSString)
- (NSString*)stringRepresentation
{
CGFloat components[10];
[self getComponents:components];
NSMutableString *string = [NSMutableString string];
for (int i = 0; i < [self numberOfComponents]; i++) {
[string appendFormat:@"%f ", components[i]];
}
[string deleteCharactersInRange:NSMakeRange([string length]-1, 1)]; // trim the trailing space
return string;
}
+ (NSColor*)colorFromString:(NSString*)string forColorSpace:(NSColorSpace*)colorSpace
{
CGFloat components[10]; // doubt any color spaces need more than 10 components
NSArray *componentStrings = [string componentsSeparatedByString:@" "];
int count = [componentStrings count];
NSColor *color = nil;
if (count <= 10) {
for (int i = 0; i < count; i++) {
components[i] = [[componentStrings objectAtIndex:i] floatValue];
}
color = [NSColor colorWithColorSpace:colorSpace components:components count:count];
}
return color;
}
@end我已经检查了上面的代码是否像广告中所说的那样编译和工作。一个小的示例程序会产生适当的输出:
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSLog(@"Red is: %@", [[NSColor redColor] stringRepresentation]);
NSLog(@"Cyan is: %@", [[NSColor cyanColor] stringRepresentation]);
NSLog(@"Read in: %@", [NSColor colorFromString:[[NSColor redColor] stringRepresentation]
forColorSpace:[NSColorSpace deviceRGBColorSpace]]);
}
return 0;
}输出:
Red is: 1.000000 0.000000 0.000000 1.000000
Cyan is: 0.000000 1.000000 1.000000 1.000000
Read in: NSCustomColorSpace Generic RGB colorspace 1 0 0 1将颜色空间存储在字符串中可能是有意义的,这样在从字符串转到颜色时就不必指定它了。但是,如果您只是要存储这些字符串并再次读取它们,则无论如何都应该使用NSData。如果您需要将颜色写入某种人类可读的文件中,或者作为调试辅助工具,则使用字符串更有意义。
发布于 2012-06-09 06:43:30
NSColor支持NSCoding protocol,因此您可以使用-encodeWithCoder:方法将其保存到归档中,并且可以使用-initWithCoder:从归档中加载它。
https://stackoverflow.com/questions/10956777
复制相似问题