Initializer element is not a compile-time constant

2019-09-01 18:47发布

问题:

I am implementing IIViewDeckController into my app.

When I am trying to replace the IBAccount to go to that screen I get an error:

Initializer element is not a compile time constant

The first section of the code is what I have now, and the UIViewController is from the IIViewDeckController that I want to use to load the FirstAccountViewController over.

-(IBAction)account{
    FirstAccountViewController* ab=[[FirstAccountViewController alloc] init];
    [self.navigationController pushViewController:ab animated:YES];
    UIViewController* leftController = [[UIViewController alloc] init]; 
}

UIViewController* leftController = [[FirstAccountViewController alloc] init]; 
IIViewDeckController* deckController =  [[IIViewDeckController alloc] initWithCenterViewController:self.centerController leftViewController:leftController
                                                                           rightViewController:rightController];

回答1:

You've declared global variables here:

UIViewController* leftController =
    [[FirstAccountViewController alloc] init]; 
IIViewDeckController* deckController =
    [[IIViewDeckController alloc] initWithCenterViewController:self.centerController leftViewController:leftController rightViewController:rightController];

and you're trying to initialize them without context (e.g. the parameters you pass -- there should be no global self).

You don't want a global variable here, and you cannot declare it as such because it cannot be initialized properly in this context, and because it's ill formed in C and ObjC.

I recommend using an ivar in this case.



回答2:

UIViewController* leftController = [[FirstAccountViewController alloc] init]; 
IIViewDeckController* deckController =  [[IIViewDeckController alloc] initWithCenterViewController:self.centerController leftViewController:leftController rightViewController:rightController];

Yeah, that's wrong -- if you want to initialize global variables on startup (although you're not at all advised to use global variables), you'll need to use an initalizer function:

UIViewController *leftController;
IIViewDeckController *deckController;

__attribute__((constructor))
void __init()
{
    leftController = [[FirstAccountViewController alloc] init]; 
    deckController =  [[IIViewDeckController alloc] initWithCenterViewController:self.centerController leftViewController:leftController rightViewController:rightController];

}