I tried to put the delegate and the datasource of my tableview into a separate class. My problem is that it always crashes with no error. This is why I can’t figure out what I’m doing wrong. Maybe someone can tell me. Maybe it is also important that I’m using ARC.
So that’s my simple code:
//ViewController.h
@interface ViewController : UIViewController {
UITableView *myTableView;
}
@property (strong, nonatomic) IBOutlet UITableView *myTableView;
@end
//ViewController.m
#import "ViewController.h"
#import "MyTableViewDatasourceDelegate.h"
@implementation ViewController
@synthesize myTableView;
- (void)viewDidLoad
{
[super viewDidLoad];
MyTableViewDatasourceDelegate *test = [[MyTableViewDatasourceDelegate alloc] init];
self.myTableView.delegate = test;
self.myTableView.dataSource = test;
}
@end
//MyTableViewDelegateDatasourceDelegate.h
@interface MyTableViewDatasourceDelegate : NSObject <UITableViewDataSource, UITableViewDelegate>
@end
//MyTableViewDatasourceDelegate.m
@implementation MyTableViewDatasourceDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
}
cell.textLabel.text = @"Test";
return cell;
}
@end
It seems that you are not referencing
testanywhere else so it gets automatically released at the end ofviewDidLoadmethod. Make sure you implementtestas an instance variable, so at least something has reference to it.It is not required for object to be an ivar for it to persist. Take a look at
delegateproperty definition:The
assignis crucial here, it means that this is a weak reference and UITableView won’t retain this object. Note, that if it said(nonatomic, retain)your code would work, but it was Apple’s design decision to implement it this way to avoid retain cycles.