Reputation: 2703
I am trying to create a custom UIView class which loads from a xim file that contains the interface for that view. I am trying to encapsulate the [NSBundle mainBundle] loadNibNamed...] within the init method of my custom view as follows:
- (id)init
{
self = [super init];
if (self)
{
NSArray* nibViews = [[NSBundle mainBundle] loadNibNamed:@"LoadingV" owner:self options:nil];
self = [(LoadingV*)[nibViews objectAtIndex: 0] retain];
}
return self;
}
I want to know:
Cheers AF
Upvotes: 1
Views: 2435
Reputation: 6082
No, this is not acceptable, it's bad practice and you actually have a memory leak there.
Better way to do this is to use a pattern called "factory".
Example:
@interface CustomView: UIView
@end
@implementation CustomView
- (void)awakeFromNib {
// custom view loaded from nib
}
@end
@interface UIView (Nib)
+ (UIView *)viewFromNib:(NSString *)nibName bundle:(NSBundle *)bundle;
@end
@implementation UIView (Nib)
+ (UIView *)viewFromNib:(NSString *)nibName bundle:(NSBundle *)bundle {
if (!nibName || [nibName length] == 0) {
return nil;
}
UIView *view = nil;
if (!bundle) {
bundle = [NSBundle mainBundle];
}
// I assume, that there is only one root view in interface file
NSArray *loadedObjects = [bundle loadNibNamed:nibName owner:nil options:nil];
view = [loadedObjects lastObject];
return view;
}
@end
Usage:
// CustomView.xib contains one View object with its class set to "CustomView"
CustomView *myView = (CustomView *)[UIView viewFromNib:@"CustomView" bundle:nil];
Upvotes: 7