【问题标题】:NSMutableData Plist for NSMutableDictionaryNSMutableDictionary 的 NSMutableData Plist
【发布时间】:2012-03-17 05:19:16
【问题描述】:

我正在通过 NSURLConnection 将 plist 加载到 NSMutableData 中。 完成后,我想将 PLIST 读入 NSMutableDictionary。 然后将对象添加到我的数组中以在表格视图中显示它们。 但目前我不知道如何将 NSMutableData 中的数据提取到我的 NSMutableDictionary 中。 如果我将本地数据保存为 iPhone 上的某个文件夹中的 plist,然后将 plist 读入我的字典,它就可以工作。但是没有办法直接做到这一点吗?

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    receivedData = [[NSMutableData alloc] initWithData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{

    NSData *data = [[NSMutableData alloc] initWithData:receivedData];

    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];


    NSDictionary *myDictionary = [unarchiver decodeObjectForKey:@"Beverage"];

    [unarchiver finishDecoding];

    beverageArray = [[NSMutableArray alloc] init];

    beverageArray = [myDictionary objectForKey:@"Beverage"];

    NSLog(@"%@", beverageArray);

}

在使用 NSURLConnection 之前,我使用了这个方法:

- (void) makeDataBeverage {

    beverageArray = [[NSMutableArray alloc] init];

    NSMutableDictionary *beverageDic = [[NSMutableDictionary alloc]initWithContentsOfURL:[NSURL URLWithString:NSLocalizedString(@"beverage", nil)]];

    beverageArray = [beverageDic objectForKey:@"Beverage"];

现在我也想使用 NSURLConnection。

【问题讨论】:

  • 错误的代码格式,我的克星。所以我们又见面了......不过,说真的,请在发布之前处理您的代码格式,谢谢!
  • 您有用于传输数据的模板吗?是xml文档吗?
  • 抱歉代码不好......只是一个初学者......加载的数据是一个带有字典和数组的plist
  • 坦率地说,我不知道正确的答案,因为我从来没有“手动”解析过 XML。如果我不得不在不知道如何在 Objective-C 中解析 XML 的情况下寻求快速解决方案,我会将数据保存到文件中,然后使用 dictionaryWithContentOfFile 创建字典。

标签: iphone nsurlconnection nsdata


【解决方案1】:

假设您拥有完整的数据 (*),您需要查看 NSPropertyListSerialization 类。它的+propertyListWithData:options:format:error: 方法应该可以为您提供所需的内容,您可以使用 options 参数以可变字典或数组的形式获取结果。

(*)听起来你有完整的数据,因为你说你可以将它写入一个文件,然后使用dictionaryWithContentsOfFile: 或类似方法读取它,但看起来你不能保证得到它来自您显示的代码。您正在-connection:didReceiveData: 中创建一个新数据,但是当数据分段到达时,可以多次调用该委托方法。 (我猜它只是碰巧在您的测试中全部到达......这可能并不总是正确的,尤其是在移动设备上。)相反,您可能希望在启动 @ 时创建一个空的可变数据987654326@(或-connection:didReceiveResponse:),追加到-connection:didReceiveData:,解析到-connectiondidFinishLoading:。甚至更好,因为属性列表解析器无论如何都无法处理部分数据,如果您的目标是 iOS 5.0+,请使用新的 +[NSURLConnection sendAsynchronousRequest:queue:completionHandler:]

【讨论】:

  • 感谢您的帮助。你看 NSPropertyListSerialization 是对的。我就是这样做的,效果很好。 NSError *error; NSData * tempData = [[NSData alloc] initWithData:receivedData]; NSPropertyListFormat plistFormat; NSDictionary *temp = [NSPropertyListSerialization propertyListWithData:tempData options:NSPropertyListImmutable format:&plistFormat error:&error]; beverageArray = [temp objectForKey:@"Beverage"];
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多