如何在核心数据上以字符串格式存储UIColor?

时间:2016-01-12 08:26:09

标签: ios

如何在核心数据中存储颜色。

UIColor *color=[UIColor grayColor];
NSData *theData = [NSKeyedArchiver archivedDataWithRootObject:color];

我试过它对我不起作用。

2 个答案:

答案 0 :(得分:0)

您可以将UIColor转换为组件,然后将其存储:

UIColor *orgColor = [UIColor blackColor];
const CGFloat *colorComponents = CGColorGetComponents(orgColor.CGColor);// RGBA
NSInteger count = CGColorGetNumberOfComponents(orgColor.CGColor);
CGFloat r, g, b, a; // save to db
if (count == 2) {
    r = g = b = colorComponents[0];
    a = colorComponents[1];
}else if (count == 4) {
    r = colorComponents[0];
    g = colorComponents[1];
    b = colorComponents[2];
    a = colorComponents[3];
}else{
    NSLog(@"What is this?");
}

然后你可以将r.g.b.a转换回你的UIColor对象:

UIColor *newColor = [[UIColor alloc] initWithRed:r green:g blue:b alpha:a];

如果有必要,你可以使用0xFF将rgb转换为NSInteger用于Coredata:

NSInteger colorInteger = ((NSInteger)(r*0xFF)<<(8*3)) 
                       + ((NSInteger)(g*0xFF)<<(8*2)) 
                       + ((NSInteger)(b*0xFF)<<(8*1)) 
                       + ((NSInteger)(a*0xFF)<<(8*0));

答案 1 :(得分:0)

最后我明白了。它运作得很好。

NSManagedObject *newDevice;

- (NSManagedObjectContext *)managedObjectContext {

    NSManagedObjectContext *context = nil;

    id delegate = [[UIApplication sharedApplication] delegate];

    if ([delegate performSelector:@selector(managedObjectContext)])

 {
        context = [delegate managedObjectContext];

    }

    return context;

}


CGColorRef colorRef = [UIColor grayColor].CGColor;

NSString *colorString = [CIColorcolorWithCGColor:colorRef].stringRepresentation;

NSManagedObjectContext *context = [self managedObjectContext];
newDevice = [NSEntityDescription insertNewObjectForEntityForName:@"ImageDetail" inManagedObjectContext:context];

NSData *imageData = UIImagePNGRepresentation(_imageView.image);

[newDevice setValue:colorString forKey:@"color"];