问题
I receiving data from URL, put it in NSDictionary, and then I need to create NSArray for each tags. My NSDictionary looks like:
(
{
id = {
text = 1;
};
logo = {
text = "url 1";
};
name = {
text = "some name 1";
};
},
{
id = {
text = 2;
};
logo = {
text = "url 2";
};
name = {
text = "some name 2";
};
},
{
id = {
text = 3;
};
logo = {
text = "url 3";
};
name = {
text = "some name 3";
};
}
)
I want to have array like that: arrLogo = (@"url 1", @"url 2", "url 3").
I'm doing next:
arrName=[[dict objectForKey:@"name"] valueForKey:@"text"];
But Xcode gives me an error:*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM objectForKey:]: unrecognized selector sent to instance
Problem in the code that I'm trying to initialize an arrays, it's look like that my dict consist of arrays. How do I extract the data correctly?
回答1:
For this you have to iterate through object of Array that you have. You can use fast enumeration as
for(object in JsonArray){
NSString *value = [object valueForKey:@"logo"]valueForKey:@"text"]];
//Add this value to your array
}
}
Hope this helps.
回答2:
The JSONResponse you have get is NSArray
not NSDictionary
You can parse you json response like this ...
NSMutableArray * tmpAry = your json response;
NSMutableArray * urlAry = [[NSMutableArray alloc] init];
for (int i=0; i<tmpAry.count; i++) {
NSMutableDictionary * tmpDictn = [tmpAry objectAtIndex:i];
[urlAry addObject:[[tmpDictn objectForKey:@"logo"] valueForKey:@"text"]];
}
NSLog(@"urlAry : %@",urlAry);
Log will display :
urlAry : (
url 1,
url 2,
url 3
)
来源:https://stackoverflow.com/questions/20772126/initialize-nsarray-with-data-from-nsdictionary