Tag Archives: NSMutableArray

For loops, if statements and nested loops

In this tutorial I will demonstrate the use of “for” loops and “if” statements. Basically a “for” loop means a section of code will loop, or repeat itself for so long as a specific condition is true. So for example, if I wrote a for loop that said in pseudo code “for so long as integer x is less than integer y perform task z and each time task z is performed increase integer x by +1″. So here what would happen that if I had integer y set to 10, and x to 0, the loop would perform task z 10 times. Each time it performs the task integer x would be incremented by +1 and once x = y the loop would end. In this tutorial we are creating a simple “password cracker” app. It’s going to take a string value entered into a text field, break it up into individual characters, then we test each character for a match to a set of pre defined characters. If it matches, we rebuild the string piece by piece. It’s an inefficient way of copying a string of course, we could just take the password string and re-print it to the screen. This isn’t so much a practical application but rather a demonstration of how for loops and if statements can be used, as well as how to separate an NSString into it’s individual characters and place those into a NSMutableArray. So here’s the basic code :-

- (void)viewDidLoad
    [super viewDidLoad];
	// initialize array of characters to be checked
    _codeBreakLabel.text = @"";
    charactersArray = [[NSArray alloc] initWithObjects:@"a", @"b", @"c", @"d", @"e", @"f", @"g", @"h", @"i", @"j", @"k", @"l", @"m", @"n", @"o", @"p", @"q", @"r", @"s", @"t", @"u", @"v", @"w", @"x", @"y", @"z", @"A", @"B", @"C", @"D", @"E", @"F", @"G", @"H", @"I", @"J", @"K", @"L", @"M", @"N", @"O", @"P", @"Q", @"R", @"S", @"T", @"U", @"V", @"W", @"X", @"Y", @"Z", @"1", @"2", @"3", @"4", @"5", @"6", @"7", @"8", @"9", @"0", @"%", @"$", @"#", nil];
- (void)didReceiveMemoryWarning
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
- (IBAction)decodePassword:(id)sender {
    [self splitString];
- (void) splitString {
    //initialize mutable array to store each string object
    NSMutableArray *stringArray = [[NSMutableArray alloc]init];
    //iterate through the string in the password field
    for (int i=0;i<[_passwordField.text length];i++) {
        //obtain each character in the string and palce it to the mutable array
       NSString *ch = [_passwordField.text substringWithRange:NSMakeRange(i, 1)];
        [stringArray addObject:ch];
    NSLog(@"%@", stringArray);
    //proceed to next method passing the mutable array
    [self testString:stringArray];
- (void) testString:(NSMutableArray*)stringArray {
    NSString *resultString = @"";
    //iterate through the characters in the password string array
    for (NSString *stringChar in stringArray) {
        //iterate through the characters in the character array
        for (NSString *testChar in charactersArray) {
            //if the character tested matches the character entered update result string
            if ([stringChar isEqualToString:testChar]) {
                resultString = [NSString stringWithFormat:@"%@%@", resultString, testChar];
                NSLog(@"%@", resultString);
    //print result string to the screen
    _codeBreakLabel.text = resultString;

here’s the project file

Game Tutorial Part 18 – Editing the questions array

In this tutorial we will edit the NSMutableArray that contains the questions to include the users correct/incorrect answer and score.

As we already have an NSMutableArray that contains the 10 questions for the game, there is no point in creating another array that duplicates this information. It’s unnecessary and creates additional memory overhead in the game that we don’t need. As much as possible when programming you want to avoid recreating or duplicating information and objects, instead re-use them, or in this case, modify it to suit your new purpose.

For each question, we will make a mutable copy of the questions NSDictionary. At the start of the game we have 10 dictionaries each one containing the correct answer and the image reference. At the end of the game, we will have the same 10 dictionaries, but each one will have two new keys. An NSNumber that denotes a BOOL value (0 or 1) to show whether the player answered right or wrong, and a second NSNumber value that will be the players score for that question.

We can then use this array to populate the UITableView that is displayed at the games conclusion which will show each question, the correct answer, whether the user got it right or wrong, and their score for that question. We will cover populating the UITableView in the next tutorial. For now, we will simply NSLog the new NSMutableArray of questions with the new dictionaries that contain the new keys.

Here’s the answer method with the new additions

- (void) answerMethod:(int)answerBtn {
    if (answerBtn == random) {
        int maxScore = 10000;
        int userScore = maxScore - (questionTimerCounter*1000);
        NSLog(@"%d", userScore);
        runningScore = runningScore + userScore;
        NSLog(@"running score %d", runningScore);
        NSMutableDictionary *question = [[NSMutableDictionary alloc] init];
        question = [[questionsArray objectAtIndex:loopCounter]mutableCopy];        
        [question setObject:[NSNumber numberWithBool:YES] forKey:@"correct"];
        [question setObject:[NSNumber numberWithInt:userScore] forKey:@"score"];
        [questionsArray replaceObjectAtIndex:loopCounter withObject:question];
    else {
        NSMutableDictionary *question = [[NSMutableDictionary alloc] init];
        question = [[questionsArray objectAtIndex:loopCounter]mutableCopy];        
        [question setObject:[NSNumber numberWithBool:NO] forKey:@"correct"];
        [question setObject:[NSNumber numberWithInt:0] forKey:@"score"];
        [questionsArray replaceObjectAtIndex:loopCounter withObject:question];
    [self revealAnswer];


iOS Game Tutorial Part 10 – answers

In this part of the tutorial we use another NSObject Subclass. This time however we are returned an NSArray of two potential answers that will also be displayed to our UILabel’s together with the correct answer. After the previous tutorial you should already be familiar with how are creating those NSObject Subclass and returning to our main game view controller the NSMutableArray object ┬áthat contains the objects we require.

Here’s the project file so you can follow along with our tutorial yourself.