开发者

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?


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.


Set the boolean value in your viewDidLoad

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


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


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;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜