views:

27

answers:

1

If I want to set my delegate and datasource for my uitableview my app crashes. What I'm doing wrong?

- (void)loadView {
 NSLog(@"AddListViewController");
 ShareListViewController *shareListViewController = [[ShareListViewController alloc] init];

 UITableView *shareListView = [[UITableView alloc]initWithFrame:CGRectMake(100, 30, 100,     200) style:UITableViewStylePlain];

 shareListView.delegate = shareListViewController;
 shareListView.dataSource = shareListViewController;


 [self.navigationController.view addSubview:shareListView];

 [shareListViewController release];
 }

And my ShareListViewController

@interface ShareListViewController : UITableViewController <UITableViewDelegate, UITableViewDataSource>{

 }

 @end

It also not working if I remove the protocols.

Thx for your help

A: 

You are releasing the shareListController controller. This is wrong, since both, that dataSourceproperty as well as the delegate property of a table view are declared as having retention policy assign, which means, that they do not retain their values. This is the responsibility of client application/view controller.

@property(nonatomic, assign) id<UITableViewDelegate> delegate
@property(nonatomic, assign) id<UITableViewDataSource> dataSource

See the UITableView Reference.

The best approach seems to be to declare an ivar in your view controller like:

@interface MyViewController: UIViewController {
    ... other stuff ...
    UITableView* shareListView;
    ShareListController* shareListController;
}
... more stuff ...
@end

In MyViewController's viewDidLoad (or, wherever else you set up the table view) alloc/init the shareListController as usual, but instead of releasing the object after you have set up the dataSource and delegate properties, you remember the reference (you still own it) in the shareListController ivar.

Finally, in the view controller's dealloc method, do:

- (void) dealloc {
    ... release other stuff ...
    shareListView.delegate = nil;      // Really, really defensive
    shareListView.dataSource = nil;    // here, but it won't hurt
    [shareListView release];
    [shareListController release];
    [super dealloc];
}
Dirk
I thought the simplest way would be to do a simple autorelease. But that don't helps either. What would you recommend?
gabac
Oh yes. Sorry totally not got it! Thanks a lot! Grüsse aus der Schweiz
gabac
Grüße in die Schweiz :-)
Dirk