views:

34

answers:

1
  1. I created a new Class named CustomToolbar
  2. Then i created an empty nib, added a toolbar to it, and set the toolbar class to "CustomToolbar".

What is the proper way of initializing CustomToolbar In code so that my class uses the nib file?

I already have written the code to do that but i know it's not the correct way and it has a leak.

@interface CustomToolbar : UIToolbar {
}
@property (nonatomic, retain) IBOutlet UIBarButtonItem *button;
@end

@implementation CustomToolbar
- (id)initWithDelegate
{
     NSArray *objects = [[NSBundle mainBundle]
      loadNibNamed:@"CustomToolbar" 
      owner:nil 
      options:nil];
    if (self = (CustomToolbar*) [objects objectAtIndex:0])
    {
        //do some work here
    }
    return self;
}
@end
+1  A: 

The NIB will call initWithCoder: on your custom class, like this:

- (id)initWithCoder:(NSDecoder*)aDecoder {
    self = [super initWithCoder:aDecoder];
    if( self ) {
        // Do something
    }
    return self;
}

If you really want to load it the way you do now, you need to retain the object returned from loadNibNamed.

aegzorz
thanks, 1 question, I don't see the nib name in the code you provided. so how does it know which nib to use? and what is NSDecoder, how can i create it and pass it to my init method? thanks
aryaxt
In the example I posted, the NIB loads your class, not you directly. So if possible you would just use CustomToolbar in IB where you want it.
aegzorz