2014-02-06 65 views
0

我正在與BigNerdRanch ios應用程序書一起工作。在第一章中,它將硬編碼到代碼文件中的問題作爲一個小測驗應用程序。如果應用程序成功運行,它應該說在控制檯displaying question: "What is blah blah?",但是當我運行的應用程序,它說數組元素爲空

displaying question: (null) 

換句話說,(空)的出現,而不是從陣列的問題。

編譯時沒有錯誤顯示。我想知道這是否與我的XCode使用Main.storyboard文件而不是xib和nib文件相結合,以及視圖控制器使用似乎期望nib文件的方法這一事實,即

- (id)initWithNibName:(NSString *)nibNameOrNil bundle: 

任何幫助,將不勝感激。這是所有的代碼。

iosQuizViewController.h

#import <UIKit/UIKit.h> 

@interface iosQuizViewController : UIViewController 

iosQuizViewController.h

{ 
    int currentQuestionIndex; 

    NSMutableArray *questions; 
    NSMutableArray *answers; 

    IBOutlet UILabel *questionField; 
    IBOutlet UILabel *answerField; 
} 

- (IBAction)showAnswer:(id)sender; 
- (IBAction)showQuestion:(id)sender; 

@end 

iosQuizViewController.m

#import "iosQuizViewController.h" 

@interface iosQuizViewController() 

@end 

@implementation iosQuizViewController 

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{ 
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
    if (self) { 
     questions = [[NSMutableArray alloc] init]; 
     answers = [[NSMutableArray alloc] init]; 
     [ questions addObject:@"What is 7 +7"]; 
     [ answers addObject:@"14"]; 

     [questions addObject:@"What is the capital of Vermont?"]; 
     [answers addObject:@"Montpelier"]; 

     [questions addObject:@"From what is cognac made?"]; 
     [answers addObject:@"Grapes"]; 

    } 
    return self; 
} 

- (IBAction)showQuestion:(id)sender 
{ 
    currentQuestionIndex++; 
    if (currentQuestionIndex == [ questions count]){ 
     currentQuestionIndex = 0; 
    } 
    NSString *question = [ questions objectAtIndex:currentQuestionIndex]; 
    NSLog(@"displaying question: %@", question); 
    [questionField setText: question]; 
    [answerField setText:@"???"]; 

} 

- (IBAction)showAnswer:(id)sender 
{ 
    NSString *answer = [ answers objectAtIndex:currentQuestionIndex]; 

    [answerField setText:answer]; 
} 


@end 
+1

最有可能的問題是因爲你的'initWithNibName:bundle:'方法永遠不會被調用,所以'questions'永遠不會被初始化。也許你應該使用'initWithCoder:'。 – rmaddy

+0

我的猜測是「問題」是零,因爲它從未初始化。 –

回答

0

我刪除initWithNibName:捆的方法和把這些代碼內viewDidLoad中

- (void)viewDidLoad 
{ 
    if (self) 
    { 
     // Create two arrays and make the pointers point to them 
     questions = [[NSMutableArray alloc] init]; 
     answers = [[NSMutableArray alloc] init]; 

     // Add questions and answers to the array 
     [questions addObject:@"What is 7 + 7?"]; 
     [answers addObject:@"14"]; 

     [questions addObject:@"What is the capital of Vermont?"]; 
     [answers addObject:@"Montpelier"]; 

     [questions addObject:@"What is cognac made from?"]; 
     [answers addObject:@"Grapes"]; 
    } 

} 
+1

不要忘記在方法的頂部放置[super viewDidLoad]。 – daveMac

+0

有需要檢查'self'。 – rmaddy