some_id
some_id

Reputation: 29896

Create a new ViewController object only if it doesnt exist

I use the following code to bring up a view

-(IBAction) openSomeView{
SomeView *sv = [[SomeView alloc]initWithNibName:@"SomeView" bundle:nil];
[self presentModalViewController:sv animated:NO];
[sv release];

}

How can I detect if this view has been created already and if so, then just show it now create a new object?

Thanks

Upvotes: 0

Views: 605

Answers (3)

Gyani
Gyani

Reputation: 2241

first declare in @interface

SomeView *sv; 

and the you can check it

-(IBAction) openSomeView{
if(sv==nil)
sv = [[SomeView alloc]initWithNibName:@"SomeView" bundle:nil];
[self presentModalViewController:sv animated:NO];
[sv release];
}

Upvotes: 1

kovpas
kovpas

Reputation: 9593

I have a couple of heavy-weight view controllers in my app. Right now I'm handling this situation as follows:

  • save MyViewController to appDelegate

  • in "openSomeView" method I'm checking if MyViewController was already created, if no - create it:

    -(IBAction) openSomeView {
        MyAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    
    
    
        if ( !appDelegate.myViewController ) {
            appDelegate.myViewController = [[SomeViewController alloc] initWithNibName:@"SomeViewController" 
                                                                                bundle:nil];
        }
    
    
        [self presentModalViewController:appDelegate.myViewController animated:NO];
    }
    

Upvotes: 0

jv42
jv42

Reputation: 8593

You cannot create more than one instance using this code, since you present modally the view controller.

Else, you'd probably keep a member variable in your class and check it against nil.

EDIT: or you can implement the 'Singleton' design pattern, if that's the meaning you search.

Upvotes: 1

Related Questions