Store and load UIColor from a .plist file

I have been looking for this for some time without success. My question is: is there an easy way to store and retrieve UIColors such as [UIColor blackColor] or [UIColor colorWithRed:0.38 green:0.757 blue:1 alpha:1]; in the .plist file in my application directory?

+8
objective-c uicolor plist
source share
2 answers

according to this discussion you have two options:

  • Store as NSData in the data field of the .plist file
  • Store as a representation of a UIColor string

NSData option p>

 NSData *theData = [NSKeyedArchiver archivedDataWithRootObject:[UIColor greenColor]]; 

NSString Option

 NSString *color = @"greenColor"; [UIColor performSelector:NSSelectorFromString(color)] 

more details here: http://www.iphonedevsdk.com/forum/iphone-sdk-development/27335-setting-uicolor-plist.html

+6
source share

If you want to keep him human, read. I made a category for this:

 @implementation UIColor (EPPZRepresenter) NSString *NSStringFromUIColor(UIColor *color) { const CGFloat *components = CGColorGetComponents(color.CGColor); return [NSString stringWithFormat:@"[%f, %f, %f, %f]", components[0], components[1], components[2], components[3]]; } UIColor *UIColorFromNSString(NSString *string) { NSString *componentsString = [[string stringByReplacingOccurrencesOfString:@"[" withString:@""] stringByReplacingOccurrencesOfString:@"]" withString:@""]; NSArray *components = [componentsString componentsSeparatedByString:@", "]; return [UIColor colorWithRed:[(NSString*)components[0] floatValue] green:[(NSString*)components[1] floatValue] blue:[(NSString*)components[2] floatValue] alpha:[(NSString*)components[3] floatValue]]; } @end 

The same formatting used by NSStringFromCGAffineTransform. This is actually part of the representative of the larger plist object in [eppz! Kit on GitHub] [1].

+4
source share

All Articles