views:

703

answers:

3

I was previously using initWithContentsOfURL to download a plist into an NSDictionary, but this hangs the UI when run on the same thread so now I have moved to NSURLConnection the issue is that I can no longer call a method to init the NSDictionary with NSMutableData. What is the best way to take NSMutableData and place it into an NSDictionary?

A: 

Without knowing exactly what you're trying to do, I'm going to take a stab at this; even if it doesn't work, I'm sure you can adapt it for your purposes.

NSString *s = [[NSString alloc] initWithBytes:[mutableData bytes] length:[mutableData length] encoding:NSUTF8StringEncoding];
NSString *path = NSTemporaryDirectory();
path = [path stringByAppendingPathComponent:@"tmpfile.txt"];
if ([s writeToFile:path atomically:NO encoding:NSUTF8StringEncoding error:nil]) {
    NSDictionary *d = [[NSDictionary alloc] initWithContentsOfFile:path];
}

In plain English, create a string from the given data, write that out to a temp file, and then load the temp file into an NSDictionary object.

That code is far from perfect (needs stuff like error checking, etc.) but it may get you started.

Caveat: I've been writing Cocoa software for several years, but I've never touched an iPhone, so that's a guess.

mipadi
+2  A: 

What you need is NSPropertyListSerialization:

NSDictionary *myDict = [NSPropertyListSerialization propertyListFromData:myData mutabilityOption:NSPropertyListImmutable format:nil errorDescription:nil];

Is the simpliest option.

Farcaller
A: 

Does your NSDictionary have other data that you need to preserve?

In the connection:didReceiveResponse: method (delegate of NSUrlConnection), you can copy your old NSDictionary into a NSMutableDictionary and then insert the URL response data into it as well. Then convert the NSMutableDictionary into a new NSDictionary.