13.07.2015 Views

Beginning Objective-C pdf - EBook Free Download

Beginning Objective-C pdf - EBook Free Download

Beginning Objective-C pdf - EBook Free Download

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 9: Writing an Application 305The error’s userInfo could be passed directly into these methods, but if something within itdoesn’t implement the NSCoder protocol, the entire dictionary will fail to encode. As a result,it is better to encode each item individually, replacing it with the base-64 encoded string andmodifying its key with a special prefix. The code in Listing 9-37 shows a method that implementsthis behavior: given a dictionary, it will check each key/value pair for JSON compatibility and anyincompatible values will be either encoded as described above or will be replaced with the resultof sending them the -description message.Listing 9-37. Encoding a Dictionarystatic NSString * APErrorEncodedKeyPrefix = @"com.apress.beginning-objective-c.base64.";NSDictionary * EncodedDictionary(NSDictionary * source){NSMutableDictionary * result = [NSMutableDictionary new];[source enumerateKeysAndObjectsUsingBlock: ^(id key, id obj, BOOL *stop) {if ( [NSJSONSerialization isValidJSONObject: obj] == NO ){if ( [obj conformsToProtocol: @protocol(NSCoding)] == NO ){// use the description insteadobj = [obj description];}else{// encode the object if possibleNSString * str = Base64String(obj);if ( str == nil ){// error encoding somewhere further down the chain// use the description againobj = [obj description];}else{// it encoded nicelyobj = str;}}}// modify the key to denote that this value is encodedkey = [APErrorEncodedKeyPrefix stringByAppendingString: key];}// place the key & value into the dictionaryresult[key] = obj;}];With this done, the final NSError category methods are those shown in Listing 9-38.www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!