heinst
heinst

Reputation: 8786

How to set text of each cell in a table objective c

I am getting questions from a server using a php script. I am setting the number of cells according to the number of questions, but when I write to the cells, it only outputs 1 question. If I use a for loop, the cells are blank, but if I set the number it repeats the same question according to how many questions are in the database. Heres the code:

    NSString *numOfQuestionsURL = @"http://**.***.**.**/count.php";
    NSData *dataURLforSize = [NSData dataWithContentsOfURL:[NSURL URLWithString: numOfQuestionsURL]];
    NSString *serverOutputforSize = [[NSString alloc] initWithData:dataURLforSize encoding:NSASCIIStringEncoding];
    int numOfQuestions = [serverOutputforSize intValue];
    for(int i = 0; i <= numOfQuestions; i++)
    {
        _hostStr = @"http://**.***.**.**/getQuestion.php?num=";
        _appendString = [[NSNumber numberWithInt:i] stringValue];
        _hostStr = [_hostStr stringByAppendingString: _appendString];
    }
    NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString: _hostStr]];
    NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding:NSASCIIStringEncoding];
    result.textLabel.text = serverOutput;

_appendString = [[NSNumber numberWithInt:i] stringValue]; is where you tell the script what question you want to retrieve.

Upvotes: 0

Views: 85

Answers (1)

Ishu
Ishu

Reputation: 12787

you need to use this code like this

- (NSInteger)tableView:(UITableView *)tableView 
 numberOfRowsInSection:(NSInteger)section {

    NSString *numOfQuestionsURL = @"http://**.***.**.**/count.php";
        NSData *dataURLforSize = [NSData dataWithContentsOfURL:[NSURL URLWithString: numOfQuestionsURL]];
        NSString *serverOutputforSize = [[NSString alloc] initWithData:dataURLforSize encoding:NSASCIIStringEncoding];
        return [serverOutputforSize intValue];
}





- (UITableViewCell *)tableView:(UITableView *)tableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  //make cell

 _hostStr = @"http://**.***.**.**/getQuestion.php?num=";
        _appendString = [[NSNumber numberWithInt:indexPath.row] stringValue];
        _hostStr = [_hostStr stringByAppendingString: _appendString];
 NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString: _hostStr]];
    NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding:NSASCIIStringEncoding];
cell.textLabel.text = serverOutput;

  return cell;
}

Also you can load data in background and maintain an array of question and populate in table.that makes your table smooth . currently your table behaves jerky.

Upvotes: 1

Related Questions