[iphone] How can I convert NSDictionary to NSData and vice versa?

I am sending NSString and UIImage using bluetooth. I decided to store both in a NSDictionary and then convert the dictionary to NSData.

My question is how to convert NSDictionary to NSData and visa versa?

This question is related to iphone objective-c ios nsdictionary

The answer is


NSDictionary from NSData

http://www.cocoanetics.com/2009/09/nsdictionary-from-nsdata/

NSDictionary to NSData

You can use NSPropertyListSerialization class for that. Have a look at its method:

+ (NSData *)dataFromPropertyList:(id)plist format:(NSPropertyListFormat)format
                              errorDescription:(NSString **)errorString

Returns an NSData object containing a given property list in a specified format.


NSDictionary -> NSData:

NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:yourDictionary forKey:@"Some Key Value"];
[archiver finishEncoding];
[archiver release];

// Here, data holds the serialized version of your dictionary
// do what you need to do with it before you:
[data release];

NSData -> NSDictionary

NSData *data = [[NSMutableData alloc] initWithContentsOfFile:[self dataFilePath]];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
NSDictionary *myDictionary = [[unarchiver decodeObjectForKey:@"Some Key Value"] retain];
[unarchiver finishDecoding];
[unarchiver release];
[data release];

You can do that with any class that conforms to NSCoding.

source


In Swift 2 you can do it in this way:

var dictionary: NSDictionary = ...

/* NSDictionary to NSData */
let data = NSKeyedArchiver.archivedDataWithRootObject(dictionary)

/* NSData to NSDictionary */
let unarchivedDictionary = NSKeyedUnarchiver.unarchiveObjectWithData(data!) as! NSDictionary

In Swift 3:

/* NSDictionary to NSData */
let data = NSKeyedArchiver.archivedData(withRootObject: dictionary)

/* NSData to NSDictionary */
let unarchivedDictionary = NSKeyedUnarchiver.unarchiveObject(with: data)

Please try this one

NSError *error;
NSDictionary *responseJson = [NSJSONSerialization JSONObjectWithData:webData
                                options:NSJSONReadingMutableContainers
                                error:&error];

Use NSJSONSerialization:

NSDictionary *dict;
NSData *dataFromDict = [NSJSONSerialization dataWithJSONObject:dict
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];

NSDictionary *dictFromData = [NSJSONSerialization JSONObjectWithData:dataFromDict
                                                             options:NSJSONReadingAllowFragments
                                                               error:&error];

The latest returns id, so its a good idea to check the returned object type after you cast (here i casted to NSDictionary).


Examples related to iphone

Detect if the device is iPhone X Xcode 8 shows error that provisioning profile doesn't include signing certificate Access files in /var/mobile/Containers/Data/Application without jailbreaking iPhone Certificate has either expired or has been revoked Missing Compliance in Status when I add built for internal testing in Test Flight.How to solve? cordova run with ios error .. Error code 65 for command: xcodebuild with args: "Could not find Developer Disk Image" Reason: no suitable image found iPad Multitasking support requires these orientations How to insert new cell into UITableView in Swift

Examples related to objective-c

Adding a UISegmentedControl to UITableView Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Warp \ bend effect on a UIView? Use NSInteger as array index Detect if the device is iPhone X Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3 ITSAppUsesNonExemptEncryption export compliance while internal testing? How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem? Change status bar text color to light in iOS 9 with Objective-C

Examples related to ios

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Examples related to nsdictionary

How to append elements into a dictionary in Swift? Converting NSString to NSDictionary / JSON convert NSDictionary to NSString How do I deserialize a JSON string into an NSDictionary? (For iOS 5+) How to use NSJSONSerialization adding multiple entries to a HashMap at once in one statement How can I convert NSDictionary to NSData and vice versa? How to add to an NSDictionary NSDictionary to NSArray? NSDictionary - Need to check whether dictionary contains key-value pair or not