I have started a new iOS “Empty Application“-template project. When I put this code inside of the application:didFinishLaunchingWithOptions: method, it works fine:
CGRect frame = CGRectMake(10, 10, 300, 25);
UILabel *helloLabel = [UILabel new];
[helloLabel setFrame:frame];
helloLabel.text = @"Hello iPhone!";
[self.window addSubview:helloLabel];
But what I really want to do is make an “addHello” class method in another class, so that what shows up in application:didFinishLaunchingWithOptions: is just:
[MyOtherClass addHello];
This is what I’ve tried putting in the other class:
+ (void) addHello {
CGRect frame = CGRectMake(10, 10, 300, 25);
UILabel *helloLabel = [UILabel new];
[helloLabel setFrame:frame];
helloLabel.text = @"Hello iPhone!";
UIWindow *window = [[UIApplication sharedApplication] keyWindow];
[window addSubview:helloLabel];
}
But that doesn’t work. What am I supposed to do?
My guess would be that [[UIApplication sharedApplication] keyWindow] is coming back nil in your code because you are calling your addHello method before the UIWindow’s makeKeyAndVisible method has not been called. I wonder if this would work:
In your appDidFinishLaunching method:
and then your MyOtherClass