user2014474
user2014474

Reputation: 1117

Adding a UITableView in a UIviewController

I have a UIViewController (ViewControllerA), and in this UIViewController I would like to add a UITableView subview that occupies part of the screen (named TableLoadGroupMembersViewController). I have already created the class for the UITableView, called TableLoadGroupMembersViewController.

In ViewControllerA.h I have imported TableLoadGroupMembersViewController in the following way:

#import "TableLoadGroupMembersViewController.h"

In ViewcontrollerA.m I want to create the UITableView through code when a button is pressed. I would like the UITableView to load the content from TableLoadGroupMembersViewController. How can I set the UITableView to read the information of the TableLoadGroupMembersViewController?

I tried in this way:

UITableView* tableVIEW = [[UITableView alloc]init];
TableLoadGroupMembersViewController* tableDelegate = [[TableLoadGroupMembersViewController     alloc] init];
[tableVIEW setDelegate:tableDelegate];
[tableVIEW setDataSource:tableDelegate];

[self.view addSubview:tableVIEW]; 

But it makes the app crash. How should I do it?

EDIT:

This is the error given:

0x387209b:  movl   8(%edx), %edi   ....  Thread 1 EXE Bad access

Upvotes: 0

Views: 949

Answers (1)

Matthias Bauch
Matthias Bauch

Reputation: 90117

a UITableView does not retain its dataSource or delegate, those are only assigned.

So if you use ARC your TableLoadGroupMembersViewController instance gets deallocated when you exit the method were you create the tableView. After the instance gets deallocated dataSource and delegate point to an invalid memory address (because their @property is assign and not weak)

You can make TableLoadGroupMembersViewController* tableDelegate a strong instance variable, then it won't get deallocated.

Something like this.

// .h
@property (strong, nonatomic) TableLoadGroupMembersViewController* tableDelegate; 

// .m

UITableView* tableVIEW = [[UITableView alloc]init];
TableLoadGroupMembersViewController* tableDelegate = [[TableLoadGroupMembersViewController     alloc] init];
self.tableDelegate = tableDelegate;
[tableVIEW setDelegate:tableDelegate];
[tableVIEW setDataSource:tableDelegate];

[self.view addSubview:tableVIEW]; 

Upvotes: 1

Related Questions