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];

tips & tricks

Join 7,719 other subscribers

interview questions


Algorithm Android Android Studio API APP Programming Apps blogging Browser CheatSheets Code Config CSS DATABASE dsa error Features HTML HTML5 IDE installation Interview Questions IOS iPhone javascript Mac objective-c OneDrive OS Placeholder Programming quicktips SDK SEO Settings SMO SQL swift swiftUI Teams Tips & Tricks Tools UI Web Wordpress Xcode


Archives

Leave a Reply

Your email address will not be published. Required fields are marked *

Discover more from CODE t!ps

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

Continue reading