I have a working code (programmed by a tutorial) but like to dive in a little deeper.
Following situation:
I have an array with questions and one array with answers
When user clicks the show question button the method looks where we are in the array and displays either the next question in the array or go back to the beginning and show the
first question we have in our array.
H FILE:
#import <UIKit/UIKit.h>
@interface QuizAppDelegate : NSObject <UIApplicationDelegate>
{
IBOutlet UIWindow *window;
NSMutableArray *answers;
NSMutableArray *questions;
IBOutlet UILabel *answersField;
IBOutlet UILabel *questionsField;
int currentQuestionIndex;
}
@property (retain, nonatomic) UIWindow *window;
- (IBAction)showQuestion:(id)sender;
- (IBAction)showAnswer:(id)sender;
@end
M FILE (just the method of the button)
- (IBAction)showQuestion:(id)sender
{
// Step to the next question
currentQuestionIndex++;
// Am I past the last question?
if (currentQuestionIndex == [questions count]) {
// Go back to the first question
currentQuestionIndex = 0;
}
// Get the string at that index in the questions array.
NSString *question = [questions objectAtIndex:currentQuestionIndex];
// Displaying the string in the questions field.
[questionsField setText:question];
// Clear the answer field:
[answersField setText:@"???"];
}
All works but I don’t understand where the connection is between the
int variable currentQuestionIndex and the index within the NSMutableArray.
Currently when my int currentQuestionIndex reports back a 2 I get the question stored
in the array at position number 2 but how it that possible?
For me it looks like that we haven’t connected the int variable currentQuestionIndex
with the index in the array we have just declared that there is an int variable
in the header file.
Maybe a silly question…. or is it just important what actual number I get back?
For example I get a 2 back from an int so I can refer to 2 in the array and there is no
requirement to attach/connect these.
Hope you can follow 😉
Not exactly sure what you are trying to say. But
questionsis an array. Arrays are accessed through indexes. i.e. first element at 0, second at 1 etc.So your
currentQuestionIndexis acting as a number to access that location in that array. Also instead of doing this –if (currentQuestionIndex == [questions count]) {
// Go back to the first question
currentQuestionIndex = 0;
}
use
modulus–