0

这是我的问题。

我无法将我的 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?

4

2 回答 2

2

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

 NSArray *array = [NSArray arrayWithContentsOfFile:myPath];

 NSData *data = array[0];
于 2013-11-14T17:10:57.233 回答
0

为什么是NSArray和 JSON?

[dict writeToFile:[self getSaveFilePath] atomically:YES];

NSDictionary *restoredDictionary = [NSDictionary  dictionaryWithContentsOfFile:[self getSaveFilePath]];
于 2013-11-14T17:27:28.237 回答