Установить делегат UITableView и источник данных

Это моя проблема: у меня в раскадровке есть этот маленький UITableView: введите описание изображения здесь

И это мой код:

SmallTableViewController.h

#import <UIKit/UIKit.h>
#import "SmallTable.h"

@interface SmallViewController : UIViewController

@property (weak, nonatomic) IBOutlet UITableView *myTable;

@end

SmallTableViewController.m

#import "SmallViewController.h"

@interface SmallViewController ()

@end

@implementation SmallViewController
@synthesize myTable = _myTable;

- (void)viewDidLoad
{
    SmallTable *myTableDelegate = [[SmallTable alloc] init];
    [super viewDidLoad];
    [self.myTable setDelegate:myTableDelegate];
    [self.myTable setDataSource:myTableDelegate];

    // Do any additional setup after loading the view, typically from a nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

@end

Теперь, как вы видите, я хочу установить экземпляр с именем myTableDelegate в качестве делегата и источника данных myTable.

Это источник класса SmallTable.

SmallTable.h

#import <Foundation/Foundation.h>

@interface SmallTable : NSObject <UITableViewDelegate , UITableViewDataSource>

@end

SmallTable.m

@implementation SmallTable

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return 5;
}

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

    // Configure the cell...
    cell.textLabel.text = @"Hello there!";

    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"Row pressed!!");
}

@end

Я реализовал все методы UITableViewDelegate и UITableViewDataSource, которые нужны приложению. Почему он просто вылетает до появления представления ??

Спасибо!!


person Marco Manzoni    schedule 29.06.2012    source источник
comment
Можете ли вы также добавить журналы сбоев?   -  person rishi    schedule 29.06.2012
comment
Проверьте обсуждение в потоке - http://stackoverflow.com/questions/254354/uitableview-issue-when-using-separate-delegate-datasource   -  person rishi    schedule 29.06.2012
comment
@Marco Manzoni: У тебя есть решение?   -  person Gaurav Borole    schedule 06.01.2015


Ответы (5)


Рикстер прав. Но я думаю, вам нужно использовать квалификатор strong для вашего свойства, поскольку в конце вашего viewDidLoad метода объект все равно будет освобожден.

@property (strong,nonatomic) SmallTable *delegate;

// inside viewDidload

[super viewDidLoad];
self.delegate = [[SmallTable alloc] init];    
[self.myTable setDelegate:myTableDelegate];
[self.myTable setDataSource:myTableDelegate];

Но есть ли причина использовать для вашей таблицы отдельный объект (источник данных и делегат)? Почему бы вам не установить SmallViewController как источник и делегат для вашей таблицы?

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

static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

// Configure the cell...
cell.textLabel.text = @"Hello there!";

dequeueReusableCellWithIdentifier просто извлекает из «кэша» таблицы ячейку, которая уже была создана и которую можно использовать повторно (это во избежание потребления памяти), но вы ее не создали.

Где ты делаешь alloc-init? Вместо этого сделайте это:

static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(!cell) {
    cell = // alloc-init here
}
// Configure the cell...
cell.textLabel.text = @"Hello there!";

Кроме того, скажите numberOfSectionsInTableView вернуть 1 вместо 0:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}
person Lorenzo B    schedule 29.06.2012

Предположительно вы используете ARC? Ваш myTableDelegate упоминается только в локальной переменной в viewDidLoad - как только этот метод завершается, он освобождается. (В шаблоне делегат / источник данных объекты не владеют своими делегатами, поэтому ссылки табличного представления на ваш объект являются слабыми.) Я бы не ожидал, что это само по себе вызовет сбой, но, вероятно, это ключ к вашей проблеме.

person rickster    schedule 29.06.2012
comment
Хорошо, я только что создал новый делегат @property (weak, nonatomic) SmallTable *; Теперь приложение не вылетает, но ... таблица пуста! Не могу понять почему ... - person Marco Manzoni; 29.06.2012

setDelegate не удержит делегата.

И

numberOfSectionsInTableView метод должен возвращать 1 вместо 0;

person Siva    schedule 29.06.2012

(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 0;
}

Количество секций должно быть установлено не менее одного

person Softec    schedule 30.11.2013

Делегат объекта UITableView должен использовать протокол UITableViewDelegate. Необязательные методы протокола позволяют делегату управлять выбором, настраивать заголовки и нижние колонтитулы разделов, помогать удалять методы.

введите описание изображения здесь

person Tulasi Narayana Dumpala    schedule 19.06.2013