从URL下载plist并将其解析为NSMutableDictionary?

时间:2010-11-12 07:57:39

标签: iphone objective-c nsarray plist nsmutabledictionary

HI伙计们〜

这是我从URL下载plist的方式

NSURLRequest *theRequest=[NSURLRequest requestWithURL:setDefaultPwdAndSnURL                                              cachePolicy:NSURLRequestUseProtocolCachePolicy
                         timeoutInterval:60.0];
NSData    *returnData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:nil error:nil];
NSString *listFile = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

[listFile dataUsingEncoding:NSUTF8StringEncoding];
NSArray *plistData = [listFile propertyList];

这是我得到的结果

plistdata is(
        {
        sn = 1;
        pwd = 123;
    }
)

我想将其保存到NSMutableDictionary

NSArray *paths      = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *docPath    = [paths objectAtIndex:0];
 NSString *filePath   = [docPath stringByAppendingPathComponent:@"DevicePassword.plist"];
 NSMutableDictionary *dictread  = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];

 NSMutableDictionary *device_serialnumber = [NSMutableDictionary dictionaryWithObject:[[plistData objectAtIndex:0]valueForKey:@"sn"]
                      forKey:@"serial_number"];

 NSMutableDictionary *device_password = [NSMutableDictionary dictionaryWithObject:[[plistData objectAtIndex:0]  valueForKey:@"pwd"]
                   forKey:@"password"];
 [dictread addEntriesFromDictionary:device_serialnumber];
 [dictread addEntriesFromDictionary:device_password];               
 [dictread writeToFile:filePath atomically:YES];

但我Log(@"dictread is :%@",dictread);

得到了dictread :( NULL)

.......所以,我说这是一个无关紧要的事情????

请帮我解决这个问题.... @ _ @

非常感谢〜

注:

我更改了一些初始值并将其记录下来检查

NSMutableDictionary *device_serialnumber = [NSMutableDictionary dictionaryWithObject:@"123"
                      forKey:@"serial_number"];

 NSMutableDictionary *device_password = [NSMutableDictionary dictionaryWithObject:@"456"
                   forKey:@"password"];

我有两个字典“device_serialnumber”和“device_password”

但是“dictread”仍然是(NULL)

我是否给错了函数添加对象????

2 个答案:

答案 0 :(得分:2)

不应该使用initWithContentsOfFile初始化

dictread:因为该文件尚不存在。如果文件有错误(无法将其作为字典读取)或文件不存在,这将为dictread返回nil。请尝试使用此初始化程序。

NSMutableDictionary *dictread  = [[NSMutableDictionary alloc] initWithCapacity:[plistdata count]];

答案 1 :(得分:1)

你也可以说:

[[plistData objectAtIndex:0] writeToFile:filePath atomically:YES];

但这会阻止您更改密钥的名称。