本文介绍了[__NSCFArray objectForKey:]:无法识别的选择器发送到实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从字典中获取特定键的值,但我得到一个[__NSCFArray objectForKey:]:无法识别的选择器发送到实例
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSDictionary * avatars = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
NSLog(@response :::%@,avatars);
if(avatars){
NSDictionary * avatarimage = [avatars objectForKey:@ - image];
NSString * name = [avatars objectForKey:@name];
}
}
我NSLog我的化身字典,我的结果是: / p>
(
{
created_at=2013-06-06T11:37:48Z;
id = 7;
image = {
thumb = {
url =/uploads/avatar/image/7/thumb_304004-1920x1080.jpg;
};
url =/uploads/avatar/image/7/304004-1920x1080.jpg;
};
name = Drogba;
updated_at=2013-06- 06T11:37:48Z;
}
)
解决方案
问题是你有一个 NSArray
不是 NSDictionary
。 NSArray
的计数为1,并包含 NSDictionary
。
NSArray * wrapper = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
NSDictionary * avatars = [wrapper objectAtIndex:0];
要遍历数组中的所有项,数组。
NSArray * avatars = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
for(NSDictionary * avatar in avatars){
NSDictionary * avatarimage = avatar [@image];
NSString * name = avatar [@name];
//您的代码的剩余
}
:我也从
-objectForKey:
切换到[]语法。我更喜欢这个。I am trying to get a value for a particular key from a dictionary but i get a "[__NSCFArray objectForKey:]: unrecognized selector sent to instance "
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{ NSDictionary *avatars = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil]; NSLog(@"response:::%@", avatars); if(avatars){ NSDictionary *avatarimage = [avatars objectForKey:@"- image"]; NSString *name = [avatars objectForKey:@"name"]; } }
I NSLog my avatars Dictionary and my result is:
( { "created_at" = "2013-06-06T11:37:48Z"; id = 7; image = { thumb = { url = "/uploads/avatar/image/7/thumb_304004-1920x1080.jpg"; }; url = "/uploads/avatar/image/7/304004-1920x1080.jpg"; }; name = Drogba; "updated_at" = "2013-06-06T11:37:48Z"; } )
解决方案The problem is you have a
NSArray
not anNSDictionary
. TheNSArray
has a count of 1 and contains anNSDictionary
.NSArray *wrapper= [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil]; NSDictionary *avatars = [wrapper objectAtIndex:0];
To loop through all items in the array, enumerate the array.
NSArray *avatars= [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil]; for (NSDictionary *avatar in avatars) { NSDictionary *avatarimage = avatar[@"image"]; NSString *name = avatar[@"name"]; // THE REST OF YOUR CODE }
NOTE: I also switched from
-objectForKey:
to [] syntax. I like that better.这篇关于[__NSCFArray objectForKey:]:无法识别的选择器发送到实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!