我正在使用BigNerdRanch ios应用程序书。在第一章中,它创建了一个小问答应用程序,将问题硬编码到代码文件中。如果应用程序成功运行,它应该在控制台中说displaying question: "What is blah blah?"
,但是当我运行应用程序时它会说
displaying question: (null)
换句话说,(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
答案 0 :(得分:0)
我删除了initWithNibName:bundle方法并将该代码放在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"];
}
}