VansFannel
VansFannel

Reputation: 45921

initialize instance variables on Objective-C

I'm developing an iPhone 3.1.3 application and I have the following header file:

#import <UIKit/UIKit.h>

@interface VoiceTest01ViewController : UIViewController {
    IBOutlet UITextView *volumeTextView;
    BOOL isListening;
    NSTimer *soundTimer;
}

@property (nonatomic, retain) IBOutlet UITextView *volumeTextView;
@property (nonatomic, retain) NSTimer *soundTimer;

- (IBAction)btnStartClicked:(id)sender;

@end

And .m file is:

#import "VoiceTest01ViewController.h"

@implementation VoiceTest01ViewController

@synthesize volumeTextView;
@synthesize soundTimer;

...

How can I set isListening up to false at start?

Upvotes: 2

Views: 5333

Answers (4)

William Hu
William Hu

Reputation: 16149

1) init is a good place, like below, but if you are using story board this init method won't be called.

- (id) init {
    self = [super init];
    if (self) {
        isListening = NO;
    }
    return self;
}

2) initWithCoder is a good place for your code if you are using storyboard of course your sdk is 3.0, i believe it has not storyboard at that time, but just in case anyone need it:

- (id) initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        isListening = NO;
    }
    return self;
}

3) If your viewcontroller will be init from nib file:

- (id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
         isListening = NO;
    }
}

Upvotes: 0

ipraba
ipraba

Reputation: 16543

Set the boolean value in your viewDidLoad

- (void)viewDidLoad {
  isListening = NO;
  //Something
}

Upvotes: 3

xlarsx
xlarsx

Reputation: 991

The default value for a BOOL field is False, but it's a good place set it in the "viewDidLoad" just as @BuildSucceeded sugest

Greetings

Upvotes: 2

DarkDust
DarkDust

Reputation: 92335

All instance variables are set to 0/NULL/nil by default, which in the case of a BOOL means NO. So it already is NO (or false) by default.

If you need any other value then you need to override the designated initializer(s), most of the time init, and set the default value there.

Upvotes: 6

Related Questions