Currently I’m working on an application that will have a UITableView for a news section. I will be making an API call to retrieve the news to populate the cells in the tableView. Currently I’m returning the data via JSON and here is what the JSON response looks like: (put on newline so reading the structure was a bit easier on the eye)
[
{
"news_id": "1",
"news_title": "Sample headline",
"news_date": "2012-12-19",
"news_news": "news article 1",
"news_priority": "3"
},
{
"news_id": "2",
"news_title": "On the Outside, Looking in",
"news_date": "2012-11-20",
"news_news": "news article 2",
"news_priority": "2"
},
{
"news_id": "3",
"news_title": "Fla. Plans to Mark Death Penalty's Return",
"news_date": "2012-12-23",
"news_news": "news article 3",
"news_priority": "1"
}
]
Before JSON encoding via php my array looks like so:
Array
(
[0] => Array
(
[news_id] => 1
[news_title] => Sample headline
[news_date] => 2012-12-19
[news_news] => news article 1
[news_priority] => 3
)
[1] => Array
(
[news_id] => 2
[news_title] => On the Outside, Looking in
[news_date] => 2012-11-20
[news_news] => news article 2
[news_priority] => 2
)
[2] => Array
(
[news_id] => 3
[news_title] => Fla. Plans to Mark Death Penalty's Return
[news_date] => 2012-12-23
[news_news] => news article 3
[news_priority] => 1
)
)
I’m storing the response by doing the following:
// populate the dictionary with the json response.
NSDictionary *data = [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:&error];
return data;
// model has a method to construct the url request/connection etc
NSDictionary *newsDict = [model makeServerAPICall:kURL postMessage:@"method=getNews"];
NSString *string = [newsDict objectForKey:@"news_id"];
Up to this point everything is appearing to be fine except when I try to access an element inside of the array I get this crash with error:
-[__NSArrayM objectForKey:]: unrecognized selector sent to instance 0xab13a40
Even though this is an NSDictionary. I’m quite confused at this point because “data” is an NSDictionary.
I’m trying to setup my tableView with the returned data having the news_title be listed in the cell and when selected will push to a detail view displaying the relative data for that article. I’ve made many API calls where the returned data is very simple JSON format. This is my first attempt at extracting the data containing multiple arrays from a JSON response. Honestly at this point I do not know where else to go from here. Any help would be much appreciated.
You are quiet confused.
[model makeServerAPICall:kURL postMessage:@"method=getNews"];will NOT RETURN a dictionary.So This code will solve your problem.
That will solve your problem.