2014-02-06 61 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