Setting up an independent delegate?
Its common for the dataSource and delegate to be the same object, its also common for this object to be the viewController.
In all the info/tutorials that I hav开发者_C百科e seen online delegates are always setup as above. If I wanted to create my own class instead can anyone give me any pointers as to how I might do that. Where does that object get instantiated, how do you connect the dataSource and delegate items etc. I am using UITableView to test this.
There's really two answers to this question :
1) If all the tutorials do it one way, why do it another?
2) A UITableView delegate is just any object which conforms to the UITableViewDelegate protocol. You would create it like so . . .
- (void) viewDidLoad {
MyDelegate *delegate = [[[MyDelegate alloc] init] autorelease];
self.myTableView.delegate = delegate;
}
assuming that MyTableViewDelegate implemented the UITableViewDelegate protocol.
You should just need to set the dataSource and delegate properties of your UITableView to the object(s) that you want to perform those roles. Make sure that your new class implements the UITableViewDelegate and UITableViewDataSource protocols in its header file:
@interface MyTableDelegate : NSObject <UITableViewDelegate, UITableViewDataSource>
Where you allocate this object is dependent on your app architecture. The object could be contained in a NIB file or it could be allocated at the same time you allocate the table view controller or in the viewDidLoad method of the controller that allocates your table:
// Create the delegate object and retain a reference to it
MyTableDelegate *tableDelegate = [[MyTableDelegate alloc] init];
self.tableDelegate = tableDelegate;
Then for example, if you are using a navigation controller you might so something like this to create your table and push it onto the stack:
// Create the table view controller
MyTableViewController *viewController = [[MyTableViewController alloc] initWithNibName:@"MyTableView" bundle:nil];
// Set the delegate and data source
viewController.tableView.delegate = tableDelegate;
viewController.tableView.dataSource = tableDelegate;
// push the table view controller onto the naviagtion controller stack
[[self navigationController] pushViewController:viewController animated:YES];
// Clean up resources
[viewController release];
The MyTableDelegate class must as a minimum contain the mandatory methods:
tableView:cellForRowAtIndexPath
tableView.numberOfRowsInSection
精彩评论