I am trying to fill the cells of a dynamic tableview with a NSDictionary I believe, here is my method to fill the tableview:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
ResultsCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
NSData *jsonData = self.responseFromServer;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:nil];
NSArray *results = [json objectForKey:#"myData"];
for (NSDictionary *item in results) {
cell.title.text =[[item objectForKey:#"title"]objectAtIndex:indexPath.row];
}
// Configure the cell...
return cell;
}
If I just have
cell.title.text =[item objectForKey:#"title"];
almost works but all my titles are the same. But how it is currently I get the error:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString objectAtIndex:]: unrecognized selector sent to instance 0x7612940'
and im not sure what it means or how to fix it.
It seems like your Dictionary is actually an array of Dictionaries each with the key #"Title".
What you are doing right now is getting the String of each element and trying to get the index of indexPath.row, but strings do not have that method.
Since you only need the object at index indexPath.row, you can replace the whole for loop with the following line of code:
cell.title.text = [[results objectAtIndex:indexPath.row] objectForKey:#"title"];
Also, as Nicholas Hart said, in order to improve performance by a lot you should put the following lines in the code when you receive the json object so that it is only done once, and make results an instance variable that can be accessed from the tableView's delegate methods:
NSData *jsonData = self.responseFromServer;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:nil];
NSArray *results = [json objectForKey:#"myData"];
Related
I have to following JSON response from a server:
{
"theSet": [
],
"Identifikation": 1,
"Name": "Casper",
"Adress": "Lovis 23",
"Location": "At home",
"Information": "The first, the second and the third",
"Thumbnail": "none",
}
I am retrieving the data like so:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"connectionDidFinishLoading");
NSLog(#"Succeeded! Received %d bytes of data",[data length]);
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&myError];
news = [NSArray arrayWithObjects:[res allKeys], [res allValues], nil];
NSLog(#"%#", news);
//[mainTableView reloadData];
}
Then I want to insert all the JSON data into an array, so I can display the data in my tableview.
My tableview code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MainCell"];
if(cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"MainCell"];
}
cell.textLabel.text = [[news objectAtIndex:indexPath.row] objectForKey:#"Name"];
cell.detailTextLabel.text = [[news objectAtIndex:indexPath.row] objectForKey:#"Adress"];
return cell;
}
But my app crashes with the error:
-[__NSArrayI objectForKey:]: unrecognized selector sent to instance.
How can I insert the JSON object into an NSArray, so I can display it in my tableview?
EDITED:
I reviewed your code again and what I previously answered was wrong.
When generating your news, you are putting 2 NSArray objects in it. The first containing all keys, and the second containing all values in your JSON.
In order to display the names of each object in your JSON, you should be simply doing
news = [res allKeys];
jsonResult = res;
// store your json if you want to use the values!
Note they will be unordered.
On your cell, you can do:
NSString *key = [news objectAtIndex:indexPath.row];
cell.textLabel.text = key;
id object = [jsonResult valueForKey:key];
cell.detailTextLabel.text = // do something depending on your json type which can have different values
The error you have
[__NSArrayI objectForKey:]: unrecognized selector sent to instance.
Tells you everything you need to know.
This says NSArray does not understand objectForKey. If you read the documentation provided by Apple, you will see this.
Your code
cell.textLabel.text = [[news objectAtIndex:indexPath.row] objectForKey:#"Name"];
Is expecting the news NSArray to return an object that responds to objectForKey - most likely an NSDictionary. The code you have for extracting your JSon data
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&myError];
news = [NSArray arrayWithObjects:[res allKeys], [res allValues], nil];
Is just taking all of the dictionaries and extracting the keys into the array.
You need to look at these lines of your code - this is where you are going wrong.
Look at the NSJSONSerialization reference and the releated sample code that it links to.
I found a simple solution myself, that fits my project better:
I just did the following:
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:data options:0 error:&myError];
NSArray news = [NSArray arrayWithObject:res];
and with that I am able to use the following code to display the JSON contents in my tableview.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MainCell"];
if(cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"MainCell"];
}
cell.textLabel.text = [[news objectAtIndex:indexPath.row] valueForKey:#"name"];
cell.detailTextLabel.text = [[news objectAtIndex:indexPath.row] objectForKey:#"Location"];
return cell;
}
I trying to bind the Json parse data with table view using below code and getting exception. I am using ASIHttpRequest and Json as well.
**Error details:**
webservice[2864:f803]
***
Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '-[testViewController tableView:numberOfRowsInSection:]:
unrecognized selector sent to instance 0x6ecc4e0'
***
NSString *responseString = [request responseString];
SBJsonParser *parser=[[SBJsonParser alloc]init];
NSDictionary *obj=[[NSDictionary alloc]init];
obj=[parser objectWithString:responseString error:nil];
return obj.count;
NSString *responseString = [request responseString];
SBJsonParser *parser=[[SBJsonParser alloc]init];
NSDictionary *obj=[[NSDictionary alloc]init];
obj=[parser objectWithString:responseString error:nil];
NSMutableArray *statuses = [[NSMutableArray alloc]init];
for (NSDictionary *status in obj)
{
[statuses addObject:status];
}
self.listdata=statuses;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: #"myCell"];
if (cell == nil) {
cell = [[ UITableViewCell alloc ] initWithFrame:CGRectZero];
}
NSUInteger row = [indexPath row];
cell.textLabel.text = [listdata objectAtIndex:row];
return cell;
Looks like your table view data source is not implementing the method tableView:numberOfRowsInSection:
I have a plist with dictionary.
In the dictionary i have a string called "cellPic" that have url address of an image.
I'm trying to populate my table view with images that i put on my dropbox account & read them through the plist string.
("arrayFromPlist" is my array)
The problem is that when i run it, i'm getting an error in the console:
[__NSCFDictionary objectAtIndex:]: unrecognized selector
This is my code:
-(void) readPlistFromDocs
{
// Path to the plist (in the Docs)
NSString *rootPath =
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
NSString *plistPath = [rootPath stringByAppendingPathComponent:#"Data.plist"];
NSLog(#"plistPath = %#",plistPath);
// Build the array from the plist
NSMutableArray *arrayFromDocs = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
if (arrayFromDocs)
{
NSLog(#"\n content of plist file from the documents \n");
NSLog(#"Array from Docs count = : %d", [arrayFromDocs count]);
}
arrayFromPlist = [[NSArray alloc] initWithArray:arrayFromDocs];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
// Returns the number of rows in a given section.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [arrayFromPlist count];
NSLog(#"Array SIZE = %d",[arrayFromPlist count]);
}
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
NSURL *url = [[NSURL alloc] initWithString:[[arrayFromPlist objectAtIndex:indexPath.row] objectForKey:#"cellPic"]];
NSData *urlData = [[NSData alloc] initWithContentsOfURL:url];
[[cell imageView] setImage:[UIImage imageWithData:urlData]];
return cell;
}
My other question is - how can i load the images asynchronous when i read the url from the plist string?
I tried to find an example for that but i found only asynchronous without uisng plist.
Thanks.
Change Following line
NSDictionary *arrayFromDocs = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
Best Tutorial for load the images asynchronous
Hope, this will help you..
I am getting data from server it gives in response a NSString which hase json data i want that json data to be store in an array how to do this
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(data);
NSData* data=[dataString dataUsingEncoding:NSUTF8StringEncoding];
[self performSelectorOnMainThread:#selector(fetchedData:)
withObject:data waitUntilDone:YES];
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSArray* latestLoans = [json objectForKey:#"loans"]; //2
NSLog(#"loans: %#", latestLoans); //3
}
here is the log of data which return from server
[{"CodeValue":"90658","CodeDescription":"flu shot","IsActive":"1","CodeType":"CPT","CodeID":"6","UpdateDateTime":"2012-04-02 02:09:46"}]
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSArray *dataArr=[data JSONValue];
for (int i=0; i<[dataArr count]; i++) {
NSDictionary *dict=[dataArr objectAtIndex:i];
NSString *codeV=[dict valueForKey:#"CodeValue"];
NSString *codeD=[dict valueForKey:#"CodeDescription"];
NSString *active=[dict valueForKey:#"IsActive"];
NSString *codeT=[dict valueForKey:#"CodeType"];
NSString *codeId=[dict valueForKey:#"CodeID"];
NSString *updatedTime=[dict valueForKey:#"UpdateDateTime"];
NSLog([dict description],nil);
}
NSLog(#"%#", json_string);
//May this will help you out.
Do include the JSon library classes to your project.
I am doing in this way to insert in an array but it return o object
NSDictionary *dict=[dataArr objectAtIndex:i];
SearchCode *theObject =[[SearchCode alloc] init];
theObject.codeValue=[dict valueForKey:#"CodeValue"];
theObject.codeDescription=[dict valueForKey:#"CodeDescription"];
theObject.codeType=[dict valueForKey:#"CodeType"];
theObject.codeID=[dict valueForKey:#"CodeID"];
theObject.UpdateDateTime=[dict valueForKey:#"UpdateDateTime"];
NSLog(codeType);
[cptArray addObject:theObject];
[theObject release];
theObject=nil;
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [cptArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.selectionStyle=UITableViewCellSelectionStyleGray;
cell.accessoryType = UITableViewCellAccessoryNone;
}
SearchCode *theObject =[cptArray objectAtIndex:indexPath.row];
cell.textLabel.text=theObject.codeValue; //& so on you can access any value from "theObject" here
}
If you want a more packaged solution check out: https://github.com/stig/json-framework
Its a awesome framework, to parse JSON you can just type
[string_here JSONValue];
I am trying to load JSON from a sever and then display it in a UITableView. The request goes fine however when I try to add the data to the tableview the app crashes when I call then [tableView reloadData] method is called. I have the variable jsonArray reference in the UITableView methods so that the TableView displays the contents of that variable. Is this the best way to do it and what am I doing wrong?
The connection
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
Main HTTP Callback
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
//Declare the parser
SBJsonParser *parser = [[SBJsonParser alloc] init];
jsonArray = [parser objectWithString:responseString];
[tableView reloadData];
[parser release];
[responseString release];
}
Error
2011-07-07 14:42:56.923 Viiad[16370:207] -[__NSSet0 objectAtIndex:]: unrecognized selector sent to instance 0x5a4a0b0
2011-07-07 14:42:56.925 Viiad[16370:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSSet0 objectAtIndex:]: unrecognized selector sent to instance 0x5a4a0b0'
EDIT
UITableViewMethods
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
NSArray *results = [[jsonArray valueForKey:#"Rows"] valueForKey:#"name"];
cell.textLabel.text = (NSString *)[results objectAtIndex:indexPath.row];
return cell;
}
This message
-[__NSSet0 objectAtIndex:]: unrecognized selector sent to instance 0x5a4a0b0
means that someplace in the code, the objectAtIndex: message was sent to an instance of __NSSet0. To me, that looks like you're passing around an NSSet where you're expecting an NSArray.
Set a debugger breakpoint before you call [results objectAtIndex:indexPath.row] and see what results actually contains. My guess is that the JSON parser isn't returning what you think it is. Objective-C is dynamically typed: just because you say that a variable is an NSArray type doesn't mean it can't contain some other object. If a function returns type id, there is no type information for the compiler to check at all.