Instantiating a UIView Subclass with a delegate, using a NIB file-Collection of common programming errors
Edit: moving the key point up to the top. You cannot simultaneously create an object and set it to file’s owner all in the same nib. The File’s Owner needs to be an already existing and initialized object with nil outlet ivars in order for the nib loading to hook up to the owner’s outlets properly.
Is the delegate object also in the nib? If nothing retains it (your property is ‘assign’) it may just go away at the next autorelease pool drain. Is the delegate an outlet in your nib? “nil” values in outlets after loading a nib is usually a sign that the outlets are not connected correctly. Also, it appears that you’re instantiating the nib with an owner object (self) that is not yet initialized? If so, your outlets may not be connected correctly because outlets are only connected if the corresponding value in the owner object is nil. You should have a fully initialized owner object before using it as an owner in loading a nib.
Here’s the “load this object from nib” initialization code I use in one of my projects:
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
// Initialization code.
//
[[NSBundle mainBundle] loadNibNamed:@"ScoreView" owner:self options:nil];
[self addSubview:self.view];
}
return self;
}
- (void) awakeFromNib
{
[super awakeFromNib];
[[NSBundle mainBundle] loadNibNamed:@"ScoreView" owner:self options:nil];
[self addSubview:self.view];
}
Using nibs has a built-in level of indirection that you can’t avoid. You can’t create an object and simultaneously use it as File’s Owner — the owner must already exist and be initialized (with nil outlets) at nib loading time.
Using the above code I can create my object either from code or place it directly into other nib files — a reusable UIView component.