我的代码是:
- (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;
}
如代码所示,不调用数据源方法。但是当我放
[self.view addSubView:self.tableView];
在viewWillAppear中,可以正确调用方法,当我将[self.view addSubView:self.tableView];
更改为self.view = self.tableView;
答案 0 :(得分:1)
您的代码存在的问题是init
可能会在viewDidLoad
之后调用,因此在您设置代理时,您的表格视图仍为nil
。
答案 1 :(得分:0)