Ready to Level-Up?

This just in! If your rusty iOS skills could use some refining, or if you're just starting out and you want to level-up fast, consider signing up for our upcoming iOS Screencasts

New from iOS Rocket Surgery Swift Video Tutorials: The rapidly evolving Apple-iOS ecosystem has just been thrown into tumult with the recent introduction of the Swift Programming Language. Are you ready to finally try iOS development? Are you needing to switch from Objective-C to Swift? Sign up today for our free video courses!
(By the dear folks at Swift Tutorial Videos, a sister company)

Tuesday, October 1, 2013

iOS Converting NSDictionary to NSData and Back

So, you want to convert a NSDictionary to NSData and back, eh?


There are plenty of occasions where you'd want to convert a NSDictionary to NSData. In my case, its typically when I want to create a binary-type attribute on an entity and store a JSON object that I fetched from an API. So its API => JSON => NSDictionary => NSData => Core Data Entity attribute. You can't store an NSDictionary into a binary attribute directly without jumping through some serialization hoops. Here's how to convert an NSDictionary to an NSData object:


NSData *myData = [NSKeyedArchiver archivedDataWithRootObject:myDictionary];

In fact, if you don't convert your NSDictionary to NSData before you assign it to the attribute, you'll get an error like: "Unacceptable type of value for attribute: property = "data"; desired type = NSData; given type = __NSDictionaryM;"

Of course, later you're gonna want to get that NSDictionary back out of your persistent store. Now you're dealing with an NSData object in your attribute, and you need to do the following to get it back into NSDictionary form:


NSDictionary *myDictionary = (NSDictionary *) [NSKeyedUnarchiver unarchiveObjectWithData:myNSData];


There, now you're able to passivate complex data structures into your table without a bunch of extra columns. Super useful when you want to save differentt types of objects in the same table without overloading your entity with attributes.





About Me

Easy NSDateFormatter Tool

Save yourself some time in formatting your NSDates to NSStrings, and use the Blind NSDate app, which you can download from iTunes. There's also a website where you can format your NSDates: http://www.blindnsdate.com

Popular Posts

Designed By Seo Blogger Templates