2012-04-10 51 views
1

使用xcode 4.3中的標籤式視圖應用程序。不進入我的構造函數

我只是試圖初始化我的FirstViewController的.h文件中聲明的一些變量。我試圖通過在我的.m文件中創建一個構造函數像這樣。

.h文件中:

#import <UIKit/UIKit.h> 

@interface FirstViewController : UIViewController { 

    IBOutlet UITextField *currentGuess; 
    IBOutlet UILabel *attemptsMade; 
    IBOutlet UILabel *attemptsLeft; 
    IBOutlet UITextView *hints; 
    int numberToGuess; 
    int numberOfGuessesMade; 
    int maxGuesses; 
    int maxGenNumber; 

    NSMutableArray *allGuesses; 


} 

- (id) init; 

@end 

.m文件

#import "FirstViewController.h" 

@interface FirstViewController() 

@end 

@implementation FirstViewController 

    - (id) init { 
     NSLog(@"entered constructor!"); 

     if(self = [super init]) 
     { 
      numberToGuess = 0; 
      numberOfGuessesMade = 0; 
      maxGuesses = 3; 
      maxGenNumber = 10; 
     } 

     return self; 
    } 
+0

試過下面的答案,最後使用viewDidLoad代替。 – 2013-01-20 03:45:10

回答

3

UIViewController沒有意義用init方法初始化。 Normaly你需要- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle

如果從XIB文件創建它,不是像這樣做

您需要將您的初始化代碼中 - (void)awakeFromNib-(void)viewDidLoad

像這樣的事情對你的情況

@implementation FirstViewController

- (id) awakeFromNib { 
    NSLog(@"entered XIB constructor!"); 

    numberToGuess = 0; 
    numberOfGuessesMade = 0; 
    maxGuesses = 3; 
    maxGenNumber = 10; 

} 

如果非廈門國際銀行則:

- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle { 
    NSLog(@"entered constructor!"); 

    if(self = [super initWithNibName:nibName bundle:nibBundle]) 
    { 
     numberToGuess = 0; 
     numberOfGuessesMade = 0; 
     maxGuesses = 3; 
     maxGenNumber = 10; 
    } 

    return self; 
} 

和記憶。 init不是您在OO類中學習的「真實」構造函數。

0

如果您正在使用筆尖。將調用方法awakeFromNib。還要檢查是否使用初始化方法的變體,如initWithNibName,initWithframe等。

0

您可以將代碼發佈到創建VC的位置嗎?如果從廈門國際銀行的init做到這一點就不會被調用,而不是你應該重新寫:

initWithNibName 
1

正如UIViewController documentation指出,對於UIViewController中指定的初始化是initWithNibName:bundle:。但是,根據您的視圖控制器的創建方式(例如,在代碼中或作爲故事板的一部分),這可能甚至不會被調用,而可能是initWithCoder: