Tips for Converting UIColor object to NSData

Tips for Converting UIColor object to NSData

Converting a UIColor object, view.backgroundColor, to an NSData object

/* 1. Archive into NSData object */

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:view.backgroundColor];

[dict setObject:data forKey:@”backgroundColor”];

/* 2. Unarchive from NSData object */

NSData *data = [dict objectForKey:@”backgroundColor”];

if ( data != nil ) {

view.backgroundColor = [NSKeyedUnarchiver unarchiveObjectWithData:data];

}

Code example 2: Writing an NSMutableDictionary object to a file with the converted color data stored in the dictionary

/* 1. Dictionary object and file name */

NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];

NSString *dictionaryFileName = @”…”;

/* 2. Do some dictionary stuff: adding key/object pairs */

/* … */

/* 3. UIColor object that we want to save to the file */

UIColor *myColor = [UIColor greenColor];

/* 4. Convert the UIColor object to NSData object and then add it to dictionary */

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:myColor];

[dictionary setObject:data forKey:@”myColor”];

/* 5. Write the dictionary to a file */

if ( [dictionary writeToFile:dictionaryFileName atomically:YES] == NO ) {

/* Use of NSData object instead of UIColor will avoid flowing through here */

/* ERROR: Couldn’t write to the file */

}

[dictionary release];

Scroll to Top

Discover more from CODE t!ps

Subscribe now to keep reading and get access to the full archive.

Continue reading