这是我的问题。
我无法将我的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?
答案 0 :(得分:2)
当您将NSData放入NSArray并将其用于writeToFile时,您需要首先将其作为NSArray返回,然后从该数组中获取NSData对象
NSArray *array = [NSArray arrayWithContentsOfFile:myPath];
NSData *data = array[0];
答案 1 :(得分:0)
为什么NSArray
和JSON?
[dict writeToFile:[self getSaveFilePath] atomically:YES];
和
NSDictionary *restoredDictionary = [NSDictionary dictionaryWithContentsOfFile:[self getSaveFilePath]];