Singleton causes app to crash when changing View C

2019-09-02 15:09发布

问题:

I am trying to use a singleton class to choose custom content to display based on the selection made by the user. It goes like this: a list is displayed, users select one of the rows in the list, and the app goes into another ViewController view. The ViewController used is the same for all the list options, however the content is different. Currently I managed to do this for only 1 option, and am trying to use a singleton class to tell the app which content to choose from.

This is what happens when the option "Raffles Landing Site" is chosen:

if(landmarkSelected== @"Raffles Landing Site") {
    RafflesLandmarkInfo *rafflesLandmarkInfo = [[RafflesLandmarkInfo alloc] initWithNibName:@"RafflesLandmarkInfo" bundle:nil];
    [self.navigationController pushViewController:rafflesLandmarkInfo animated:YES];
    [rafflesLandmarkInfo release];

This opens a UIWebView implemented as follows:

[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"raffles" ofType:@"html"]isDirectory:NO]]];

I created a singleton class as described here: http://www.galloway.me.uk/tutorials/singleton-classes/

I added an NSMutableString property to it and changed the previous codes to the following:

if(landmarkSelected== @"Raffles Landing Site") {
        LandmarkController* instance = [LandmarkController sharedInstance];
        [instance.activeLandmark setString:@"raffles"];
        RafflesLandmarkInfo *rafflesLandmarkInfo = [[RafflesLandmarkInfo alloc] initWithNibName:@"RafflesLandmarkInfo" bundle:nil];
        [self.navigationController pushViewController:rafflesLandmarkInfo animated:YES];
        [rafflesLandmarkInfo release];

and

 if (instance.activeLandmark ==@"raffles"){
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:instance.activeLandmark ofType:@"html"]isDirectory:NO]]];
}

but the app crashes when I select Raffles Landing Site from the list of options. The culprit seems to be

[instance.activeLandmark setString:@"raffles"];

How do I set the activeLandmark string in the first ViewController so when it loads the second ViewController it displays content based on the value set in the first ViewController?

回答1:

In your singleton, is the activeLandmark string being alloced/initialized before you try and assign to it?