2012-06-29 3 views
15

Это моя проблема: У меня есть в моей раскадровке этой маленькой UITableView: enter image description hereнабор UITableView Делегат и DataSource

И это мой код:

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 в качестве делегата и DataSource 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 метод, приложение потребность. Почему он просто падает перед представлением?

Спасибо!

+0

Могли бы вы вставить ошибку? – JonLOo

+0

Можете ли вы добавить журналы аварий? – rishi

+0

Проверить обсуждение в теме - http://stackoverflow.com/questions/254354/uitableview-issue-when-using-separate-delegate-datasource – rishi

ответ

15

rickster - правый. Но я думаю, вам нужно использовать квалификатор 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; 
} 
4

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

+0

ОК, я только что создал новый @property (слабый, неатомический) делегат SmallTable *; Теперь приложение не разбивается, но ... вид таблицы пуст! Я не могу понять, почему ... –

1

setDelegate не сохранит делегата.

И

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

0

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

enter image description here

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

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

Смежные вопросы