简体   繁体   中英

numberOfRowsInSection method is calling two times

I am developing a simple table application from appcoda. I have one confusion in numberOfRowsInSection method. When I print the values in console using NSLog in numberOfRowsInSection method the console displays the values two times instead of one times that means the numberOfRowsInSection method is called two times.

So can you tell me why this is happening?

Here is my code

@implementation ViewController {
    NSArray *recipes;
}

- (void)viewDidLoad {
    [super viewDidLoad];
     recipes = [NSArray arrayWithObjects:@"Egg Benedict", @"Mushroom Risotto", @"Full Breakfast", @"Hamburger", @"Ham and Egg Sandwich", @"Creme Brelee", @"White Chocolate Donut", @"Starbucks Coffee", @"Vegetable Curry", @"Instant Noodle with Egg", @"Noodle with BBQ Pork", @"Japanese Noodle with Pork", @"Green Tea", @"Thai Shrimp Cake", @"Angry Birds Cake", @"Ham and Cheese Panini", nil];

}

This method prints the values two times in console instead of one time

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

    NSLog(@"No of Recipe :- %d",[recipes count]);
    return [recipes count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *tableIdentifier = @"recipeCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:tableIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tableIdentifier];
    }
    cell.textLabel.text = [recipes objectAtIndex:indexPath.row];
    return cell;
}

It probably is a normal behaviour. Place a break point in numberOfRows method and have a look at the call stack. You can see that the numberOfRows gets called from two different flows by the framework itself. In my case, I can see that:

  1. Once it gets called from [UITableView didMoveToWindow]
  2. Other one from [UITableView layoutSubviews]

我认为您调用了2次reloadData方法,所以numberOfRowsInSection方法也调用了2次。

Look for the number of sections of your tableView. It must be set as 1!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM