This question is related to this one. I have two constructors:
- (id)initWithBanner:(NSMutableArray *)banners {
if ( self = [super initWithNibName:@"UIBanner" bundle:nil] ) {
testString = [[NSString alloc] initWithString:@"Banner"];
NSLog(@"Foo");
}
return self;
}
- (id)initWithPreview:(NSMutableArray *)previews {
if ( self = [super initWithNibName:@"UIBanner" bundle:nil];
testString = [[NSString alloc] initWithString:@"Preview"];
NSLog(@"Foo");
}
return self;
}
- (void)viewDidLoad {
NSLog(@"%@", testString);
}
In another object I have two instances of this class called *bannerPreview and *bannerVideo, initialized with initWithPreview and initWithVideo. Here what it happens:
In the preview constructor, I can’t access to IBOutlets, because they are nil, while they are not in the banner. But the method viewDidLoad of bannerVideo gets called BEFORE the constructor has finished, while the viewDidLoad of bannerPreview does not. I’ve added a string test in the class, and a NSLog(@”Foo”) in the two methods listed above and my output is:
2011-03-15 12:29:13.929 iUDC[2600:207] Foo
2011-03-15 12:29:13.934 iUDC[2600:207] preview
2011-03-15 12:29:15.038 iUDC[2600:207] (null)
2011-03-15 12:29:15.038 iUDC[2600:207] Foo
How should I handle this behaviour?
What you do in your
initshould be independent of what you do inviewDidLoad. Anything that is dependent onself.viewshould be done inviewDidLoad.Whether
viewDidLoadis called before or after theinithas finished is dependent on how long it takes to load the view and how long it takes to execute theinit.