Search code examples
iphoneobjective-ciosjsonuicolor

iPhone iOS how to serialize / save UIColor to JSON File?


When I need to save a color to core data, I simply use NSKeyedArchiever and then unarchieve color when I need to load the entity. However, when I try to serialize the core data entity, the process fails because it does not know how to convert the keyed archiever's NSData to a string.

What's the best way to convert a UIColor to a string representation for sending within JSON file? One solution is to store the r,g,b,a values as floats. One solution is to save it as a hex string. Both of these seem to complicate the process of color restoration

Am I missing something ? Is there an easier way to serialize a UIColor within JSON?


Solution

  • How about that:

    NSDictionary *colorData = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:100.f], @"Red",
                                   [NSNumber numberWithFloat:24.f], @"Green",
                                   [NSNumber numberWithFloat:23.f], @"Blue",
                                   [NSNumber numberWithFloat:1.f], @"Alpha", nil];
    
    NSDictionary *color = [NSDictionary dictionaryWithObject:colorData forKey:@"Color"];
    

    The result is something like:

    {"Color":{"Green":24,"Alpha":1,"Blue":23,"Red":100}}
    

    You can easily make a method that takes UIColor as an argument and return a NSDictionary, that can be serialized directly. The reverse process is the same.