[英]NSDictionary From NSMutableData
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. 我以前使用initWithContentsOfURL将plist下载到NSDictionary中,但是当在同一线程上运行时,这会挂起UI,所以现在我移到NSURLConnection了,问题是我无法再使用NSMutableData调用初始化NSDictionary的方法。 What is the best way to take NSMutableData and place it into an NSDictionary?
将NSMutableData放入NSDictionary的最佳方法是什么?
What you need is NSPropertyListSerialization: 您需要的是NSPropertyListSerialization:
NSDictionary *myDict = [NSPropertyListSerialization propertyListFromData:myData mutabilityOption:NSPropertyListImmutable format:nil errorDescription:nil];
Is the simpliest option. 是最简单的选项。
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. 用简单的英语,从给定的数据创建一个字符串,将其写到临时文件中,然后将临时文件加载到
NSDictionary
对象中。
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. 警告:我已经编写Cocoa软件已有好几年了,但是我从未接触过iPhone,所以这是一个猜测。
Does your NSDictionary have other data that you need to preserve? 您的NSDictionary是否还需要保留其他数据?
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. 在connection:didReceiveResponse:方法(NSUrlConnection的代理)中,您可以将旧的NSDictionary复制到NSMutableDictionary中,然后也将URL响应数据插入其中。 Then convert the NSMutableDictionary into a new NSDictionary.
然后将NSMutableDictionary转换为新的NSDictionary。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.