Json Parser output display in tableview - iphone

I am trying to parse using JSON Parser and the result which i get i have to put it into table view. I've passed a constant key value and a string .
Is there parsing steps wrong? or missed.
I have included the code for the JSON parser.
Thanks in advance.
SBJSON *parser = [[SBJSON alloc] init];
NSString *urlString =[NSString stringWithFormat:#"http://api.shopwiki.com/api/search?key=%#&q=%#",apiKey, string];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL: url];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSMutableArray *statuses = [[NSMutableArray alloc]init];
statuses = [parser objectWithString:json_string error:nil];
NSLog(#"Array Contents: %#", statuses);
NSMutableArray *statuses0 = [[NSMutableArray alloc]init];
statuses0 = [statuses valueForKey:#"offers"];
NSLog(#"Array Contents: %#", statuses0);
//For Title
NSMutableArray *statuses1 = [[NSMutableArray alloc]init];
statuses1 = [[[statuses valueForKey:#"offers"] valueForKey:#"offer"]valueForKey:#"title"];
NSLog(#"Array Contents 4 Title: %#", statuses1);
Here in statuses1 array i get 20 objects which are all titles, now i just want to display that titles into tableview:-
snippet code for tableview:-
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSLog(#"status count:%d",[statuses1 count]);
return [statuses1 count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"Inside Tableview");
int counter=indexPath.row;
NSString *CellIdentifier = [NSString stringWithFormat:#"%d",counter];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.selectionStyle=UITableViewCellSelectionStyleNone;
}
NSLog(#"Inside Tableview 1");
cell.textLabel.text=[statuses1 objectAtIndex:indexPath.row];
NSLog(#"Inside Tableview 2");
return cell;
}
I get Bad excess exception whten it hits on :-
cell.textLabel.text=[statuses1 objectAtIndex:indexPath.row];
Please give me the solution
thanks in advance:-

If you're getting EXC_BAD_ACCESS on that line, it's probably because statuses1 has been released by the time cellForRowAtIndexPath is called. What block of code is this line in?
NSMutableArray *statuses1 = [[NSMutableArray alloc]init];
The statuses1 variable above is local to whatever scope you've declared it in. Do you then assign it to your UITableViewController.statuses1 ivar? Is that a retained property?

Related

How to display array of JSON values in custom tableView cells

I want to pass values inside for(NSDictionary *jsonDictionary in myJsonArray) which I get in NSLog to [array addObject:[[SaveList alloc] initWithEmail:email withPhone:phone withDate:date withName:name]];
Code is here
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSError *error = nil;
NSURL *url = [NSURL URLWithString:#" http:// Some url "];
NSString *json = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:&error];
NSLog(#"\n\n JSON : %#, \n Error: %#", json, error);
if(!error)
{
NSData *jsonData = [json dataUsingEncoding:NSASCIIStringEncoding];
NSArray *myJsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
// NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
for(NSDictionary *jsonDictionary in myJsonArray)
{
NSLog(#"JSON Dictionary = %#", jsonDictionary);
NSString *name = jsonDictionary[#"Name"];
NSString *date = jsonDictionary[#"Date"];
NSString *email = jsonDictionary[#"Email"];
NSString *phone = jsonDictionary[#"Phone"];
NSLog(#"Name = %#", name);
NSLog(#"Date = %#", date);
NSLog(#"Email = %#", email);
NSLog(#"Phone = %#", phone);
}
}
});
//Table implementation
array = [[NSMutableArray alloc]init];
//**Get email, phone, date, name here**
[array addObject:[[SaveList alloc] initWithEmail:email withPhone:phone withDate:date withName:name]];
self.tableView.dataSource = self;
self.tableView.delegate = self;
Why don't you add the objects as you receive them? Since this block of code will be executed asynchronously you could prepare your array, set your tableview and then execute the block where you fill your array and refresh the tableview.
Something like this:
// Prepare your array
array = [NSMutableArray arrayWithCapacity:0];
// Set your tableview's datasource & delegate
self.tableView.dataSource = self;
self.tableView.delegate = self;
// Fetch data asynchronously
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSError *error = nil;
NSURL *url = [NSURL URLWithString:#" http:// Some url "];
NSString *json = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:&error];
NSLog(#"\n\n JSON : %#, \n Error: %#", json, error);
if(!error)
{
NSData *jsonData = [json dataUsingEncoding:NSASCIIStringEncoding];
NSArray *myJsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
NSMutableArray *tmp = [NSMutableArray arrayWithCapacity:myJsonArray.count];
for(NSDictionary *jsonDictionary in myJsonArray)
{
NSString *name = jsonDictionary[#"Name"];
NSString *date = jsonDictionary[#"Date"];
NSString *email = jsonDictionary[#"Email"];
NSString *phone = jsonDictionary[#"Phone"];
//**Get email, phone, date, name here**
[tmp addObject:[[SaveList alloc] initWithEmail:email
withPhone:phone
withDate:date
withName:name]];
}
// Reload your tableview
dispatch_sync(dispatch_get_main_queue(), ^{
array = tmp; // Or add them to your datasource array, whatever suits you...
[self.tableView reloadData];
});
}
});
set number of rows
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
[array count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
SavedList *savedList = [array objectAtIndex:indexPath.row];
cell.text = savedList.name;
}
return cell;
}
I hope it will be helpful.
// U need to reload table view data whenever you add new object in it. It does work like a thread.
dispatch_sync(dispatch_get_main_queue(), ^{
array = myJsonArray;
[self.tableView reloadData];

getting data in connectionDidFinishLoading,but ubable to use those data in cellForRowAtIndexPath method

I am developing an iphone application. In this i have to generate user profile form dynamically according to field information coming from the server.
So, if there are 5 fields in response i want ton create 5 labels from those data to display in cell of uitableview.
Not that i am getting the name of fields for user profile, not the values of profile.
I want to generate form dynamically from those data.
I'm able to get those data in NSMutableArray but in cellForRowAtIndexPath method its showing null.
How can i solve this?
My code snippet is as follow.
-(void) connectionDidFinishLoading:(NSURLConnection *)connection {
if (connection)
{
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
//You've got all the data now
//Do something with your response string
// NSLog(#"Response:%#",responseString);
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *object = [parser objectWithString:responseString error:nil];
NSString *pec_count = [object valueForKey:#"peculiarity_count"];
NSDictionary *pecs = [object valueForKey:#"peculiarities"];
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:nil];
[array addObject:#""];
for (int j= 1; j <= [pec_count integerValue] ; j++) {
NSString *val = [NSString stringWithFormat:#"%#%d",#"pec_",j];
NSString *pec_i = [pecs valueForKey:val];
NSString *modifiedString = [pec_i stringByReplacingOccurrencesOfString:#"_" withString:#" "];
NSString *capitalisedSentence = [modifiedString stringByReplacingCharactersInRange:NSMakeRange(0,1)
withString:[[modifiedString substringToIndex:1] capitalizedString]];
[array insertObject:capitalisedSentence atIndex:j];
}
self.peculiarity = array;
[self.table reloadData];
}
for (int j=0 ; j < [self.peculiarity count] ; j++) {
NSLog(#"info:%#", [self.peculiarity objectAtIndex: j]);
}
}
- (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];
UIButton *racebtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
racebtn.frame = CGRectMake(240, 7, 10, 15);
[racebtn setBackgroundImage:[UIImage imageNamed:#"select.png"] forState:UIControlStateNormal];
[racebtn addTarget:self action:#selector(selectRace:)forControlEvents:UIControlEventTouchUpInside];
NSLog(#"cell=%#",[self.peculiarity objectAtIndex:3]);
}
Any help will be appreciated.
Thank you.
in connectionDidFinishLoading: method replace the following line:
self.peculiarity = array; with,
self.peculiarity = [[NSMutableArray alloc] initWithArray:array];
and in cellForRowAtIndexPath method add the following line of code:
cell.textLabel.text = [self.peculiarity objectAtIndex:indexPath.row];
hope this will help you.
Note: If you did not allocated self.peculiarity NSMutableArray then alloc that array like bellow..
if (self.peculiarity == nil)
self.peculiarity = [[NSMutableArray alloc] init];
and then assign that array to this array like bellow..
self.peculiarity = array;
after in cellForRowAtIndexPath: method just set that value or name to the textLabel Of the UITableViewCell like bellow..
cell.textLabel.text = [self.peculiarity objectAtIndex:indexPath.row];
see whole example with that method..
- (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];
UIButton *racebtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
racebtn.frame = CGRectMake(240, 7, 10, 15);
[racebtn setBackgroundImage:[UIImage imageNamed:#"select.png"] forState:UIControlStateNormal];
[racebtn addTarget:self action:#selector(selectRace:)forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:racebtn];
cell.textLabel.text = [self.peculiarity objectAtIndex:indexPath.row];
}
return cell;
}
I already have checked all above solutions before, Then finally i got solution for this. The problem was that my cell was getting loaded before arrival of data. So i used synchronous request to the server.
Code is below for this :
NSString *path = [[NSBundle mainBundle] objectForInfoDictionaryKey:#"path"];
NSString *address = [NSString stringWithFormat:#"%#%#%#%#", path,#"users/",#"peculiarity/",self.tablename];
NSURL *URL = [NSURL URLWithString:address];
NSLog(#"%#",address);
[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[URL host]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL cachePolicy:NSURLCacheStorageAllowedInMemoryOnly
timeoutInterval:60.0];
[request setHTTPMethod:#"GET"];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (data) {
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"data:%#",responseString);
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *object = [parser objectWithString:responseString error:nil];
pecs = [object valueForKey:#"pec_values"];
for (int j =0; j < [pecs count] ; j++) {
NSLog(#"values:%#",[pecs objectAtIndex:j]);
}
self.peculiarity = array;
}
else {
// Handle error by looking at response and/or error values
NSLog(#"%#",error);
}

ios - How to load data from JSON url in UITableView?

I'm new to iPhone development,I'm trying to bind data from JSON Url in UITableview, but I'm getting an error in the below code.
- (void)viewDidLoad
{
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://80f237c226fa45aaa09a5f5c82339d46.cloudapp.net/DownloadService.svc/Courses"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
statuses = [parser objectWithString:json_string error:nil];
[self.dropdownTblView reloadData];
for (NSDictionary *status in statuses)
{
_altTitle = [status valueForKey:#"Title"];
NSLog(#"Title %#",_altTitle);
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"%d",[statuses count]);
return [statuses 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] autorelease];
}
return cell;
//Here I'm getting an error
id obj = [statuses objectAtIndex:indexPath.row];
NSString *name = [obj valueForKey:#"Title"];
cell.textLabel.text =name;
return cell;
}
This is my JSON
[
{
"Id": 1,
"Title": "Tamil to English",
"AltTitle": "த|மி|ழ்| |மூ|ல|ம்| |ஆ|ங்|கி|ல|ம்",
"Description": "Learn English through Tamil",
"Code": 1,
"Version": "1.0",
"SourceLanguageIndicator": "அ",
"TargetLanguageIndicator": "A",
"SourceLanguageCode": "ta",
"TargetLanguageCode": "en",
"Updated": "2013-02-21T03:33:19.6601651+00:00"
}
]
Any ideas? Thanks in advance.
You're returning the cell twice in the same scope, try to delete the first return cell;, also you're calling reloadData on the table just before the for loop; in this case probably the dataSource of the table is still empty, so call reloadData just after the for loop.
EDIT:
It's strange what is happening, the objectFromString must return a NSArray or a NSDictionary but it seems that is pointing to an NSSet. I can suggest 2 things in addition:
It seems that you're not usig ARC since you're calling autorelease on the UITableViewCell. In this case you're leaking parser and json_string in the viewDidLoad, so release them.
Make sure to call [super viewDidLoad]; (you're not doing this in your code).
Maybe because you set the type of obj as id. It is too generic and may not know how to respond to valueForKey. Have you tried declaring obj as an NSDictionary * instead? Like the code below:
NSDictionary *obj = [statuses objectAtIndex:indexPath.row];
NSString *name = [obj valueForKey:#"Title"];
Use the Below code in your ViewDidload and Run the Project , it will work.
Note :You're returning the cell twice, try to delete the first return
cell;
- (void)viewDidLoad
{
[super viewDidLoad];
statuses=[[NSMutableArray alloc]init];
NSURL *myURL = [NSURL URLWithString:#"http://80f237c226fa45aaa09a5f5c82339d46.cloudapp.net/DownloadService.svc/Courses"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSLog(#"Finished with status code: %i", [(NSHTTPURLResponse *)response statusCode]);
id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(#"jsonObject=%#",jsonObject);
statuses=[jsonObject mutableCopy];
[self.coursetable reloadData];
}];
NSLog(#"myURL=%#",myURL);
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"%d",[statuses count]);
return [statuses 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] ;
}
id obj = [statuses objectAtIndex:indexPath.row];
cell.textLabel.text =[obj valueForKey:#"Title"];
return cell;
}
Yes I was thinking right, statuses is not NSArray, it is NSSet so if you call objectAtIndex on NSSet it will crash.To get array convert NSSet into NSArray.
NSArray *array =[statuses allObjects];
- (void)viewDidLoad
{
NSString *dictStr=#"{\"Id\": 1,\"Title\": \"Tamil to English\",\"AltTitle\": \"த|மி|ழ்| |மூ|ல|ம்| |ஆ|ங்|கி|ல|ம்\",\"Description\": \"Learn English through Tamil\",\"Code\": 1,\"Version\": \"1.0\",\"SourceLanguageIndicator\": \"அ\",\"TargetLanguageIndicator\": \"A\",\"SourceLanguageCode\": \"ta\",\"TargetLanguageCode\": \"en\",\"Updated\": \"2013-02-21T03:33:19.6601651+00:00\"}";
NSDictionary *rootDict =[NSJSONSerialization JSONObjectWithData: [dictStr dataUsingEncoding:NSUTF8StringEncoding]
options: NSJSONReadingMutableContainers
error: nil];
NSArray *keys=[[rootDict allKeys] sortedArrayUsingSelector:#selector(compare:)];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [keys count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier=#"cellIdentifier";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell==nil) {
cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
cell.textLabel.text=[rootDict valueForKey:[keys objectAtIndex:indexPath.row]];
return cell;
}
remember rootDict and keys will be declared as global.

how to parse json string and store the object in an array in iphone

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];

iPhone UITableView populateing from connectionDidFinishLoading

I have been trying for hours to figure this out. I have some JSON from a NSURLConnection. This is working fine and I have parsed it into an array. But I can't seem to get the array out of the connectionDidFinishLoading method. I an am getting (null) in the UITableViewCell method. I am assuming this is a scope of retain issue, but I am so new to ObjC I am not sure what to do. Any help would be greatly appreciated.
Cheers.
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
SBJSON *json = [[SBJSON alloc] init];
NSDictionary *results = [json objectWithString:responseString];
self.dataArray = [results objectForKey:#"data"];
NSMutableArray *tableArray = [[NSMutableArray alloc] initWithObjects:nil];
for (NSString *element in dataArray) {
//NSLog(#"%#", [element objectForKey:#"name"]);
NSString *tmpString = [[NSString alloc] initWithString:[element objectForKey:#"name"]];
[tableArray addObject:tmpString];
}
}
- (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];
}
// Configure the cell.
//cell.textLabel.text = [self.tableView objectAtIndex:indexPath.row];
cell.textLabel.text = [self.tableArray objectAtIndex:indexPath.row];
NSLog(#"%#", tableArray);
return cell;
}
Solution:
After taking kubi and st3fan's advice with self.tableArray I found I had to reload the tableView with [self.tableView reloadData];
Get rid of the [connection release] in the 2nd line. The connection object comes in autoreleased, so this could cause crashes.
It looks like you've got a property named tableArray? If so, you're redeclaring the name in this method (you should have gotten a compiler warning).
On second thought, here's how the 2nd 1/2 of the method should look:
NSMutableArray *tmpArray = [[NSMutableArray alloc] initWithObjects:nil];
for (NSString *element in dataArray) {
[tmpArray addObject:[element objectForKey:#"name"]];
}
self.tableArray = tmpArray;
[tmpArray release];
In connectionDidFinishLoading: you use declare tableArray as a local variable. Therefore it will never be assigned to self.tableArray.
I had the same problem and I resolved it reloading the table.
I inserted this line at the end of connectionDidFinishLoading function
[self.tableView reloadData];
and it works.