Ошибка утверждения в UITableView configureCellForDisplay: forIndexPath:

Я не уверен, где ошибка здесь, посмотрев другие подобные проблемы. Я получил отказ от утверждения.

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:

Я думаю, что это что-то простое, но надеюсь, что кто-то может помочь.

Ниже мой код:

#import "StockMarketViewController.h"

@interface StockMarketViewController ()

@end


@implementation StockMarketViewController
@synthesize ShareNameText, ShareValueText, AmountText;
@synthesize shares, shareValues;


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
{
    return [shares count];

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];



    NSString *currentValue = [shareValues objectAtIndex:[indexPath row]];
    [[cell textLabel]setText:currentValue];
    return cell;

}

Ответ 1

вы никогда не создаете ячейку, вы просто пытаетесь повторно использовать выделенную ячейку. но поскольку вы никогда его не создали, их нет.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    static NSString *cellIdentifier = @"cell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
    }

    NSString *currentValue = [shareValues objectAtIndex:[indexPath row]];
    [[cell textLabel]setText:currentValue];
    return cell;
}

или попробуйте (только iOS 6 +)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    static NSString *cellIdentifier = @"cell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];

    NSString *currentValue = [shareValues objectAtIndex:[indexPath row]];
    [[cell textLabel]setText:currentValue];
    return cell;
}

из UITableView.h

- (id)dequeueReusableCellWithIdentifier:(NSString *)identifier;  // Used by the delegate to acquire an already allocated cell, in lieu of allocating a new one.
- (id)dequeueReusableCellWithIdentifier:(NSString *)identifier 
                           forIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(6_0); // newer dequeue method guarantees a cell is returned and resized properly, assuming identifier is registered

-dequeueReusableCellWithIdentifier: всегда будет нужна проверка, если ячейка была возвращена, а -dequeueReusableCellWithIdentifier:forIndexPath: может создать новый экземпляр.

Ответ 2

Если вы не определили ячейку прототипа с идентификатором @"cell" в Storyboard, вы получите ошибку утверждения при попытке удалить из нее.

Вы можете исправить это, установив свойство Identifier в ячейку прототипа (выберите ячейку и установите этот атрибут в правой панели).

Ответ 3

Очень глупая ошибка, которую я совершил, была

i не поместил UITableViewDelegate, UITableViewDataSource после имени класса контроллера, например мой код класса был класс TagsViewController: UIViewController

он должен иметь класс TagsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource

Может быть, один из вас сталкивается из-за этого, все остальные коды были в порядке.

Ответ 4

Вам нужно вызвать "initWithStyle" в пользовательском TableViewCell и снова инициализировать объекты.

Пример: файл ProductTableViewCell.m

@implementation ProductTableViewCell

- (void)awakeFromNib {
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
   [super setSelected:selected animated:animated];
}

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])
    {
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        _titleLabel = [[UILabel alloc] initWithFrame:(CGRectMake(70, 0, 320, 60))];
        [self.contentView addSubview:_titleLabel];
   }
   return self;
}

В главном файле реализации

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 
    ProductTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"productTableViewCell"];
    NSDictionary *dic = nil;
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        dic = [_filteredArray objectAtIndex:indexPath.row];
    } else {
        dic = [_originalArray objectAtIndex:indexPath.row];
    }
    cell.titleLabel.text = [dic objectForKey: @"title"];
    return cell;
}

Ответ 5

У меня была такая же ошибка, и мне удалось найти ошибку. У меня был массив для segues и просмотр названий:

NSArray *MMTitles= [NSArray arrayWithObjects:@"MainMenu",@"viewIt",@"viewNots",@"MyProfile",@"Settings",@"Instructions",@"Help", nil];
NSArray *MMSegues=[NSArray arrayWithObjects:@"MainMenu",@"MyProfileSegue",@"viewNotSegue",@"MyProfileSegue",@"SettingsTableViewSegue",@"InstructionsViewSegue",@"HelpViewSegue", nil];

self.menuItems = [[NSArray alloc]initWithObjects:MMTitles,MMSegues, nil];

Затем я использовал этот массив в качестве источника данных для моей таблицы. Ошибка, которую я получал, была связана с тем, что на самом деле у меня не было HelpViewSegue, объявленного в моей раскадровке, когда я создал экземпляр VC:

    vc = [mainStoryboard instantiateViewControllerWithIdentifier: [[self.menuItems objectAtIndex:1]objectAtIndex:indexPath.row]];

Довольно тривиальный, но это было довольно неприятно! Надеюсь, это помогло.

Ответ 6

В приведенном ниже коде вы написали @"cell" (написано с небольшим c), но вы должны использовать @"cell" (c должен быть капиталом).

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];