简体   繁体   中英

question about init and load from xib for a custom UIView

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:

  1. Is this an acceptable way of doing so? And is there any better way?
  2. Should i keep the "retain" given that i do not call [self release] in dealloc?

Cheers AF

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM