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
开发者_JAVA百科How should I handle this behaviour?
What you do in your init
should be independent of what you do in viewDidLoad
. Anything that is dependent on self.view
should be done in viewDidLoad
.
Whether viewDidLoad
is called before or after the init
has finished is dependent on how long it takes to load the view and how long it takes to execute the init
.
You've got a bug in your initWithPreview:
method. It should probably say:
[super initWithNibName:@"UIPreview" bundle:nil]
精彩评论