#import "ShowViewController.h"
@interface ShowViewController ()
- (IBAction)showQuestion:(id)sender;
- (IBAction)showAnswer:(id)sender;
@property (weak, nonatomic) IBOutlet UILabel *questionField;
@property (weak, nonatomic) IBOutlet UILabel *answerField;
@end
@implementation ShowViewController
int currentQuestionIndex ;
NSMutableArray *questions;
NSMutableArray *answers;
//id声明的是一个实例方法,而实例方法必须放在@implementation里面,放在外面就会出现 [missing context for method declaration]的错误
- (id)init
{
//调用父类实现的init方法
self = [super init];
if(self){
//创建两个数组对象,为指针赋值,指向这两个数组对象,alloc是给每一个数组里面的元素分配内存,设置了三组问题与回答
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;
}
//按索引获取questions数组中的字符串
NSString *question=[questions objectAtIndex:currentQuestionIndex];
//用问题标签显示该字符串
[self.questionField setText:question];
//将从question指针指向的地址中获取的字符串输出到控制台
NSLog(@"displaying question: %@",questions);
//输出questions数组中有多少个元素
//重置答案标签
[self.answerField setText:@"???"];
}
- (IBAction)showAnswer:(id)sender {
//得到当前问题的答案
NSString *answer=[answers objectAtIndex:currentQuestionIndex];
//用答案标签显示该答案
[_answerField setText:answer];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end