2011-03-02 38 views
2

初始化實例變量我開發一個iPhone 3.1.3應用和 我有以下的頭文件:對Objective-C的

#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 

而且.m文件是:

#import "VoiceTest01ViewController.h" 

@implementation VoiceTest01ViewController 

@synthesize volumeTextView; 
@synthesize soundTimer; 

... 

如何我可以在開始時將isListening設置爲false嗎?

+0

它將與默認NO進行初始化。 – Vladimir 2011-03-02 14:19:12

回答

3

在您的viewDidLoad

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

是的 - @ VansFannel,請務必查看UIViewController文檔,以瞭解爲什麼這是這種類的情況。 :) – 2011-03-02 14:19:09

+5

這太蹩腳了 - 不是你的答案,@iPrabu,這是正確的,但事實上,Objective-C語言不允許你指定實例變量的初始值設定項。事實上,你必須以某種操作系統和應用程序特定的方式來實現它,這只是令人傷心的事情(或者像@DarkDust所說的那樣覆蓋指定的初始化程序,但僅僅爲了添加一個簡單的'= 1'就更加痛苦了。 )。 – GaryO 2013-07-27 19:56:51

6

所有實例變量的默認設置爲0 /空/零,這在BOOL的情況下,意味着NO設置布爾值。所以它默認已經是NO(或者是false)。

如果您需要任何其他值,那麼您需要覆蓋指定的初始化程序,大部分時間爲init,並在那裏設置默認值。

2

的布爾字段的默認值是假的,但它是一個很好的地方設置中的「viewDidLoad中」就像@BuildSucceeded sugest

問候

0

1)init是個好地方,像下面,但是如果你使用的是故事板,這個init方法將不會被調用。

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

2) initWithCoder是你的代碼的好地方,如果你使用的是當然的故事板的SDK是3.0,我認爲它並沒有在那個時候故事情節,但以防萬一有人需要它:

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

3)如果您的ViewController將筆尖文件是init:

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