JSON parsing unrecognized selector sent to instance 0x8f3ab10

牧云@^-^@ 提交于 2019-12-25 02:56:08

问题


I'm trying to parse a some very basic json data, i doing the exact same whey i always do but i getting the following error:

-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x8e7d570 2014-04-30 15:04:33.699 Mensagens 2[7530:60b] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x8e7d570'

this is the GET.JSON file:

{
  "version":"6"
}

This is the code in my app where i try to get value of Version:

NSURL *url = [NSURL URLWithString:@"http://localhost/app/get.json"];

NSData *data = [NSData dataWithContentsOfURL:url];

NSMutableArray *getVersion = [[NSMutableArray alloc]init];
getVersion = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

NSString *currentVersion = [[getVersion objectAtIndex:0]objectForKey:@"version"];

NSLog(@"Version = %@", currentVersion);

I just don't see any where things are going wrong.


回答1:


It should be

NSDictionary *getVersion = [NSJSONSerialization JSONObjectWithData:data 
                                                        options:kNilOptions error:nil];
NSString *currentVersion = [getVersion objectForKey:@"version"];

or with new syntax

NSString *currentVersion = getVersion[@"version"];

because objectAtIndex means you are accessing an array but you only have a json object




回答2:


Irrespective of the type you used to declare getVersion, the below method creates NSDictionary or NSArray depending upon the data passed to this method. In your case, it seems that JSON response data is a dictionary, hence even though getVersion is declared (or for that matter even instantiated) to be NSMutableArray object, after execution of below getVersion is a NSDictionary.

getVersion = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

As answered by meda, you can use [getVersion objectForKey:@"Version"] to get what you're looking for.



来源:https://stackoverflow.com/questions/23395143/json-parsing-unrecognized-selector-sent-to-instance-0x8f3ab10

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!