我正在與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
最有可能的問題是因爲你的'initWithNibName:bundle:'方法永遠不會被調用,所以'questions'永遠不會被初始化。也許你應該使用'initWithCoder:'。 – rmaddy
我的猜測是「問題」是零,因爲它從未初始化。 –