views:

817

answers:

2

Hi all,

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..

Thanks very much..

+4  A: 

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;
}
Paul Scott
Perfect - thanks Paul.You have no idea how long I've been trying to find that in the docs and online. I find it frustratingly impossible to have to go up through the entire hierarchy of superclasses to find out the behaviour/properties of a given class.Hopefully, I'll learn little rules of thumb which will help - I'm fairly new to Obj-C.Thanks again. Much appreciated..
CapsicumDreams
+1  A: 

One common mistake that people make when they're new to Cocoa or Cocoa Touch, is to subclass when they don't actually need to. I've seen many examples of custom windows, tableviews, scrollviews and imageviews that need never have been written.

What functionality are you adding to UITableView? Are you sure that what you want to do can't be accomplished through the delegate methods, or by using a custom cell class?

NSResponder
I've added to the standard UITableView so that it sends a message to its delegate when any section header is tapped. (I'm using it to shrink that section down to reduce space).I appreciate the advice, though.. thanks..
CapsicumDreams