2012-01-12 122 views
1

QuestionsViewController.h:按鈕顯示爲空輸出

#import <UIKit/UIKit.h> 
@interface QuestionsViewController : UIViewController 
{  
    int currentQuestionIndex; 
    NSMutableArray *questions; 
    IBOutlet UILabel *questionField; 
} 

-(IBAction)showQuestion:(id)sender; 
@end 

QuestionsViewController.m:

#import "QuestionsViewController.h" 

@implementation QuestionsViewController 

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{ 
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
if (self) { 
    self.title = NSLocalizedString(@"First", @"First"); 
    self.tabBarItem.image = [UIImage imageNamed:@"first"]; 
} 
return self; 
} 

- (id)init 
{ 
// Call the init method implemented by the superclass 
self = [super init]; 
if (self) { 
// Create two new arrays and make the pointers point to them 
questions = [[NSMutableArray alloc] init]; 

    //Add questions and answers to the array 
    [questions addObject:@"Who are you?"]; 

    [questions addObject:@"Are your talking to me?"]; 

} 
// Return the address of the new object 
return self; 
} 

- (IBAction)showQuestion:(id)sender 
{ 
// Step to the next question 
currentQuestionIndex++; 

// Am I past the last question? 
if (currentQuestionIndex == [questions count]) { 
    // Go back to the first question 
    currentQuestionIndex = 0; 
} 

// Gets the string at the index in the questions array 
NSString *question = [questions objectAtIndex:currentQuestionIndex]; 

// Log the string to the console 
NSLog(@"displaying question: %@", question); 

// Display the string in the question field 
[questionField setText:question]; 
} 

// Removed ViewLifeCycle Code 

@end 

這將構建並在模擬器中運行,但是當我按下按鈕showQuestion我得到這樣的輸出:

2012-01-12 11:15:59.180 2Rounds3[1036:f803] displaying question: (null) 

我在做什麼錯?

+1

嘗試在操作方法中記錄你的數組,看看那裏有什麼? – rishi 2012-01-12 16:41:37

回答

3

我的猜測是你永遠不會打電話給-init方法。

我想你正在用-initWithNibName:bundle方法創建你的視圖控制器。我對麼?如果是這樣,你是-init方法永遠不會被調用。因此,不要在-init方法中設置實例變量questions,而是在您的主要初始化方法中執行此操作:-initWithNibName:bundle

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{ 
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
    if (self) { 
     self.title = NSLocalizedString(@"First", @"First"); 
     self.tabBarItem.image = [UIImage imageNamed:@"first"]; 

     // Create two new arrays and make the pointers point to them 
     questions = [[NSMutableArray alloc] init]; 

     //Add questions and answers to the array 
     [questions addObject:@"Who are you?"]; 

     [questions addObject:@"Are your talking to me?"]; 
    } 
    return self; 
}