0

When I do simple HelloWorld app I have problem with

[self.tableView insertRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationAutomatic]

,this method doesn't work... and i don't know why? pliz help

Code:

- (void)viewDidLoad
{
int i = 0;
[super viewDidLoad];
    while (i < 10 ) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        [self.tableView insertRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationAutomatic];
        i++;
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   static NSString *CellIdentifier = @"Cell";
   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
   cell.textLabel.text = @"HelloWorld";
   return cell;
}

App should create 10 cells with Label @"HelloWorld"

EarthUser
  • 23
  • 7

1 Answers1

3

You're going about this the wrong way. If you want 10 cells you shouldn't be trying to add them one at a time, you should just return 10 in numberOfRowsInSection, e.x:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 10;
}

Additionally, nothing will show up in the cells because you have call alloc/init on the cells in cellForRowAtIndexPath. Modify your code to do so like this:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    cell.textLabel.text = @"HelloWorld";
    return cell;
}
Mick MacCallum
  • 129,200
  • 40
  • 280
  • 281
  • `[self.tableView insertRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationAutomatic]` not doing tableView:cellForRowAtIndexPath... – EarthUser Jan 10 '13 at 20:41
  • @EarthUser I think you're missing the point here. If `numberOfRowsInSection` returns 1, the table will only have 1 cell. If your problem is that `cellForRowAtIndexPath` is never being called, then you are incorrectly settings your table view's delegate/datasource. – Mick MacCallum Jan 10 '13 at 20:43
  • http://pixs.ru/showimage/Noviy1tiff_5781402_6781571.jpg datasource is Hello World View – EarthUser Jan 10 '13 at 20:57
  • @EarthUser Sorry, since you had marked my answer as correct I thought that you fixed the problem, and I see in your screenshot that you're return 0 sections. Try changing this to return 1. – Mick MacCallum Jan 10 '13 at 21:18
  • thanks a lot for this post!!!!=) i found problem, and problem has been with CellIdentifier :D – EarthUser Jan 10 '13 at 21:28