DefenestrationDay DefenestrationDay - 1 month ago 14
Objective-C Question

How to initialize UITableView? Both from XIB and programmatically?

I have a simple request that I have spent much time on (embarrassingly)..

I have sub-classed a UITableView to add some functionality. These new features require things like NSMutableSet which require allocation/initialization.

I have put my object's initialization routine in

- (id)initWithFrame:(CGRect)frame style:(UITableViewStyle)style {


which I understood from the apple docs to correct - but this doesn't get called (determined by break-pointing on the code).

I am using IB, and have dragged a
UITableView
onto the view, and changed it's class to my new sub-class. There is no
UITableViewController
.
I have also tried:

- (void)loadView {
- (id)init {
- (id)initWithFrame:(CGRect)frame {


with no success. I would like to have this class work both with IB, and programmatically in the future. Everything works apart from the location of this initialization..

Answer

When objects load from a XIB file, they get -(id)initWithCoder:(NSCoder*)coder.

If you create objects from XIBs and programmatically, you'll need to implement both the designated initializer -initWithFrame:style: and -initWithCoder:, doing all your init stuff in each one.

Keeping those two in sync can be a pain, so most folks like to break the init stuff out into a private method, typically called -commonInit.

You can see an example of this in action in some of the Apple sample code: HeadsUpUI.

- (void)commonInit
{
    self.userInteractionEnabled = YES;
}

- (id)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame])
    {
        [self commonInit];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super initWithCoder:aDecoder])
    {
        [self commonInit];
    }
    return self;
}