tags:

views:

182

answers:

2

Hi,

I have a NSString member variable declared in the header file of the view controller:


@interface MyApprViewController : UIViewController {
 NSString *var;
        ... 
}

@property (retain) NSString *var;
...

-(IBAction)buttonPressed: (id)sender;

Inside the implementation, I use @synthesize var and try to use that var from within the implementation of the buttonPressed method, but it does not work properly and I assume it is because var was never initialized. Where can I initialize this variable? I do not want to do it inside the method; I want to do it once of course, because I will keep appending text to it:


-(IBAction)buttonPressed: (id)sender {
 NSString *input = ((UIButton *)sender).currentTitle;
 var = [var stringByAppendingString:input];
 textField.text = var;  
 }

 [input release];
}

I tried overriding the init method inside the view controller class, but it never gets called (maybe because there is no explicit initialization of the view controller class?) So, where should I initialize var so that I can use it inside the view controller class (inside the buttonPressed method)?

Thanks, Mihai

A: 

The best place would be inside your viewDidLoad or any init method you use. If you have neither, just add a method -(void)viewDidLoad to your UIViewController.

David Kanarek
Thanks, it worked!
Mihai Fonoage
+1  A: 

There are several places to initialize:

- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle

This is the designated initializer. You said you overloaded "init" which is not the designated initializer for UIViewController.

- (void)awakeFromNib

If your view controller is itself inside of a parent NIB, this method is called once the parent NIB is fully loaded and the parent NIB's outlets have all been wired.

- (void)viewDidLoad

If your view controller has a NIB, this is called when its NIB has been loaded.

- (void)loadView

If your view controller doesn't have a NIB, this is called when its view is first requested.

Rob Napier
Thank for that. I used viewDidLoad and it worked as expected.
Mihai Fonoage