这是我的问题。

我无法将plist数据(以JSON序列化)转换为NSDictionary。

为了将数据保存在我的应用程序中,我正在以这种方式写入plist文件。

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    [dict setObject:[NSNumber numberWithInt:[[MyUser sharedUser] userID]] forKey:@"userID"];
    [dict setObject:[[MyUser sharedUser] firstname] forKey:@"firstname"];
    [dict setObject:[[MyUser sharedUser] lastname] forKey:@"lastname"];
    [dict setObject:[[MyUser sharedUser] mail] forKey:@"mail"];
    [dict setObject:[[MyUser sharedUser] pwd] forKey:@"pwd"];
    [dict setObject:[[MyUser sharedUser] token] forKey:@"token"];
    [dict setObject:[[MyUser sharedUser] picture] forKey:@"picture"];

    NSData *putData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];
    NSArray *array = [[NSArray alloc] initWithObjects:putData, nil];
    [array writeToFile:[self getSaveFilePath] atomically:YES];
}


当我想从plist加载数据以获取我的NSDictionary时。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    NSString *myPath = [self getSaveFilePath];
    BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:myPath];
    if (fileExists)
    {
        NSData *data = [NSData dataWithContentsOfFile:myPath];
        NSLog(@"%@", data);
        NSString *s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@", s);
    }
    return YES;
}


s等于:(与在Fraise中打开文件时的文件内容相同)

<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
    <data>
    eyJsYXN0bmFtZSI6IkRvbm5pbmdlciIsImR0ZWxscyI6IlRPT00iLCJpc0RDYXJkUHJv
    RGVmYXVsdCI6ImluZGl2aWR1YWwiLCJzZW5kaW5nSW52aXQiOiJzbXMiLCJpc0F1dG9E
    bCI6IjAiLCJmaXJzdG5hbWUiOiJUaG9tYXMiLCJjb250YWN0TGlzdCI6eyJtZXNzYWdl
    IjoiUmVjb3JkKHMpIEZvdW5kIiwic3VjY2VzcyI6dHJ1ZSwiZGF0YSI6eyJ0b3RhbENv
    dW50IjozLC [....]
</data>
</array>
</plist>


我不知道如何处理我的字符串以将其转换为NSDictionary。
如何从plist中获取NSDictionary?

最佳答案

当您将NSData放入NSArray并使用writeToFile时,首先需要将其作为NSArray取回,然后从该数组中获取NSData对象

 NSArray *array = [NSArray arrayWithContentsOfFile:myPath];

 NSData *data = array[0];

关于ios - 来自plist文件的NSDictionary,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19983479/

10-13 03:52