今天在學習UItableView 的時候,定義了一個屬性html
1 @property (weak, nonatomic) NSMutableArray *dataList;
在ViewDidLoad方法方法中用一下方法實例化學習
1 _dataList = [NSMutableArray arrayWithCapacity:20]; 2 3 for (NSInteger i = 0; i < 20; i++) 4 5 { 6 7 Book *book = [[Book alloc]init]; 8 9 NSString *string = [NSString stringWithFormat:@"iOS進階(%ld)", i]; 10 11 [book setBookName:string]; 12 13 [book setPrice:98.98]; 14 15 [_dataList addObject:book]; 16 17 }
而後實現UItableViewDataSource代理方式atom
1 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 2 { 3 return _dataList.count; 4 } 5 6 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 7 { 8 static NSString * CellIdentifier = @"bookCell"; 9 BookCell *bookCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 10 if (bookCell == nil) 11 { 12 bookCell = [[BookCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 13 NSBundle *bundle = [NSBundle mainBundle]; 14 NSArray *array = [bundle loadNibNamed:@"BookCell" owner:nil options:nil]; 15 bookCell = [array lastObject]; 16 } 17 18 Book *book = _dataList[indexPath.row]; 19 bookCell.bookPrice.text = book.bookPrice; 20 bookCell.bookName.text = book.bookName; 21 22 return bookCell; 23 24 }
運行之後沒有任何數據,也沒有錯誤,跟蹤調試後發現-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 方法沒有執行,再繼續跟蹤,發現spa
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
2 {
3 return _dataList.count;
4 }代理
這個方法的返回值是0,即便 _dataList.count是0,爲何是0,原來在定義的時候把 _dataList 屬性寫成了weak,因此就沒有retain,要寫成strong。因爲- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 的返回值是0,因此就不會調用-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 了。調試
關於weak和strong看這篇文章http://www.2cto.com/kf/201303/192824.html;code