尝试访问值时,Nsdictionay keyvalue编码错误

时间:2015-11-05 10:01:34

标签: ios objective-c nsstring nsdictionary

{
  "gender" : "Male",
  "city" : "chenna",
  "instituteName" : "srm",
    "profileImage" : "ProfileImage",
    "dob" : "DOB",
     "emailAddress" : "saxasx",
  "isStudent" : "true",
 "studentIdValidity" : "Month2Year5",
"studentIdImage" : "IDImage",
 "name" : "xasx",
 "phoneNumber" : "9092256227"
}

     NSDictionary *dic ;
dic = [[NSUserDefaults standardUserDefaults]objectForKey:@"fizzstudentjson"];

    NSLog(@"%@",dic);

NSString *strng = [dic objectForKey:@"city"];
NSLog(@"%@",strng);

当我尝试使用我的应用时,访问nsstring中的dictonary值正在崩溃 我编写的代码帮助了我

2 个答案:

答案 0 :(得分:0)

这对我有用。

NSDictionary *dictionary = @{
    @"gender" : @"Male",
    @"city" : @"chenna",
    @"instituteName" : @"srm",
    @"profileImage" : @"ProfileImage",
    @"dob" : @"DOB",
    @"emailAddress" : @"saxasx",
    @"isStudent" : @"true",
    @"studentIdValidity" : @"Month2Year5",
    @"studentIdImage" : @"IDImage",
    @"name" : @"xasx",
    @"phoneNumber" : @"9092256227"
    };

[[NSUserDefaults standardUserDefaults] setObject:dictionary forKey:@"fizzstudentjson"];

NSDictionary *dic = [[NSUserDefaults standardUserDefaults]objectForKey:@"fizzstudentjson"];

NSLog(@"%@",dic);

NSString *strng = [dic valueForKey:@"city"];
NSLog(@"%@",strong);

<强>结果:chenna

答案 1 :(得分:0)

作为记录数据,它可能是NSString格式,而不是NSDictionary。所以你需要在使用前将它转换为NSDictionary。试试这段代码

    NSString *fizzstudentjson = [[NSUserDefaults standardUserDefaults]objectForKey:@"fizzstudentjson"];

    NSData *data = [fizzstudentjson dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

    NSString *city = dictionary[@"city"];