stucs
stucs

Reputation: 11

Whats wrong with my code,The datasource methods are not called

My code is:

- (instancetype)init {
    self = [super initWithNibName:nil bundle:nil];
    if (self) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height - 20)
                                                  style:UITableViewStylePlain];

        for (int i = 0; i < 10; i++) {
            [[LHItemSharedStore sharedStore] createItem];
        }
    }

    return self;
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    return [self init];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tableView reloadData];

}
- (void)viewDidLoad {
    [super viewDidLoad];

    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];

}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [[[LHItemSharedStore sharedStore] items]count];
}

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

As the code show, the datasource methods are not called. but when I put [self.view addSubView:self.tableView];

In viewWillAppear, the methods can be called correctly, also works when I change [self.view addSubView:self.tableView]; to self.view = self.tableView;

Upvotes: 0

Views: 87

Answers (2)

 stucs
stucs

Reputation: 11

problem solved! seems that i use self.view.fram in my init method, then loadview is called, then call viewDidLoad, in viewDidLoad the init process of _tableView is not end, so _tableView is nil. if I set self.view = self.tableView in viewDidLoad, it will be called util self.tableView is not nil. benifit i get it is that put view init into viewDidLoad.

Upvotes: 0

Bal&#225;zs Vincze
Bal&#225;zs Vincze

Reputation: 3832

The problem with your code is, that init is probably called after viewDidLoad , thus your table view is still nil when your setting the delegates.

Upvotes: 1

Related Questions