1

I have an array of questions (NSArray *questions) in a class Questions. I have a label (questionLabel) and a button (nextButton) on the View. When the button is pressed I want the label to loop through the array of questions. I made something similar on Treehouse, but they used arc4random which doesn't look good because the same question can appear multiple times in a row before changing. I want to infinitely loop, in order, through the question array. I have copied my code for the button below.

The app runs but nothing happens when I press the button. I have honestly spent two weeks searching, learning, etc. and I have found nothing to help me figure this out. Any help is very much appreciated.

This code is in the ViewController.m file:

- (IBAction)nextButton {
   NSArray *questions = [[NSArray alloc] init];
   for (NSString *nextQuestion in questions) {
       self.questionLabel.text = nextQuestion;
   }
}
1
  • Why would you do a loop when the button is tapped? You just want to set the text to the next question, not all of the questions. Commented Sep 28, 2016 at 23:25

2 Answers 2

1

I am not sure that I understand your question exactly though,
The result you want to see is this?

#import "ViewController.h"

@interface ViewController ()
@property (strong, nonatomic) IBOutlet UILabel *questionLabel;
@property (nonatomic, strong) NSArray *questions;
@end

@implementation ViewController
@synthesize questions;
@synthesize questionLabel;

- (IBAction)nextButton:(id)sender {

    /* 
        this does alloc init and return array object containing no index data.
     */
    // questions = [[NSArray alloc] init];

    for (NSString *nextQuestion in questions) {
        self.questionLabel.text = nextQuestion;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    questions = [[NSArray alloc] initWithObjects:@"Question1", @"Question2", @"Question3", @"Question4", nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


In this situation, you, of course, will get nil data inside array object index.

In your code,

- (IBAction)nextButton {
   NSArray *questions = [[NSArray alloc] init];
   for (NSString *nextQuestion in questions) {
       self.questionLabel.text = nextQuestion;
   }
}

This does alloc / init and returns NSArray reference containing empty index data whenever the button is clicked and you loop though the empty index data array object.

==========================================
Edited and Update
==========================================

//
//  ViewController.m
//  StackoverflowQuestion
//
//  Created by Seoksoon Jang on 29/09/2016.
//  Copyright © 2016 Seoksoon Jang. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
@property (strong, nonatomic) IBOutlet UILabel *questionLabel;
@property (strong, nonatomic) IBOutlet UIButton *questionButton;
@property (nonatomic, strong) NSArray *questions;
@property (nonatomic, assign) BOOL stopRequest;
@end

@implementation ViewController
@synthesize questions;
@synthesize questionLabel;
@synthesize questionButton;
@synthesize stopRequest;

#define LOOP_DELAY_TIME     0.1

- (UIColor*)generateRandcomColor {
    CGFloat hue = ( arc4random() % 256 / 256.0 );  //  0.0 to 1.0
    CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5;  //  0.5 to 1.0, away from white
    CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5;  //  0.5 to 1.0, away from black
    return randomColor = [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];
}

- (IBAction) stopButton:(id)sender {
    stopRequest = !stopRequest;
}

- (IBAction) nextButton:(id)sender {

    self.questionButton.enabled = NO;

    for (NSString *nextQuestion in questions) {

        dispatch_async(dispatch_get_main_queue(), ^{
            self.questionLabel.text = nextQuestion;
            self.questionLabel.backgroundColor = [self generateRandcomColor];
        });

        [NSThread sleepForTimeInterval:LOOP_DELAY_TIME];
    }

    if (stopRequest) {
        stopRequest = !stopRequest;

        dispatch_async(dispatch_get_main_queue(), ^{
            self.questionButton.enabled = YES;
        });

        return ;

    } else {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [self performSelector:@selector(nextButton:) withObject:nil];
        });
    }
}

- (void) viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    questions = [[NSArray alloc] initWithObjects:@"Why is Kimchi the best food in the world", @"Why is Bacon healthy?", @"Why is Pizza delicious?", @"Why is Tuna nice?", nil];    
}

- (void) didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

This is so simple UI interface and result screenshot based on this source code.


* Storyboard UI example screenshot *
enter image description here




* result *
enter image description here

==========================================
Edited and Update 2
==========================================

#import "ViewController.h"

@interface ViewController ()
@property (strong, nonatomic) IBOutlet UILabel *questionLabel;
@property (strong, nonatomic) IBOutlet UIButton *questionButton;
@property (strong, nonatomic) NSArray *questions;
@property (assign, nonatomic) NSUInteger count;
@end

@implementation ViewController
@synthesize questions;
@synthesize questionLabel;
@synthesize questionButton;
@synthesize count;

- (IBAction)nextButton:(id)sender {

    if (count >= [questions count]) {
        count = 0;
    }

    self.questionLabel.text = [questions objectAtIndex:count++];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    questions = [[NSArray alloc] initWithObjects:@"Question1", @"Question2", @"Question3", @"Question4", nil];

    count = 0;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

enter image description here

Sorry for mistaking your question.
Probably, it is not what you want again.
I'm doing just for fun. So, Don't feel burdensome.

Sign up to request clarification or add additional context in comments.

5 Comments

thanks so much for taking time to put this together. So I applied the code exactly as you have recommended, but when I press the button it just takes the label to the last object in the array. When I press the button I want the label to iterate through the array infinitely. Do you think you could help me with that? Thanks again!
okay, in the edited source, I tried it as far as I understand your question. Anyway, is this right request following your demand?
Again thanks a lot for taking the time to write this up, but only difference that I am wanting is a single click - next question, single click - next question, single click - next questions, etc. does that make sense? So the user clicks the button to get the next question in the array one at a time. But like I said I can do this using arc4random but then the same question appears multiple times in a row.
single click - next question, single click - next question, single click - next questions... one click - next questions by doing for loop iteration? could you give me your source code or project link?
That is perfect! Thanks that is exactly what I wanted the button to do. Now I need to figure out how to put the array in a new class because I intend on making several arrays with different packages of questions, so I think I should have those array placed in a class. Thanks again boraseoksoon!
0

I want you to do like this

in interface declare

int i,j;
NSArray questions;

Now in viewdidload and add all objects to array

j=0;
i=j;
questions = [[NSArray alloc]initwithObjects : "YOUR QUESTION","YOUR QUESTION"..........,nil];

Now in button action method

-(IBAction)nextButton : (sender)
{
     for (i = j; i < [questions count]; i++)
     {
        self.questionLabel.text = [quesions objecAtIndex:i];  
        j = i;
        break;
     } 
}

Hope this thing works

3 Comments

Thanks a lot for putting this together. I also tried this exactly as you have recommended, but the button just changes the label to one of the objects in the array instead of iterating through the whole array. Do have any fixes for that? Thank you!
Mainly what do you want ? As per my understanding you want to change question everytime when you clicked on button. So according to that my code is working properly
I'm sorry I meant that when I click the button it just stops on one object from the array then when i click it again nothings happens so it gets stuck on one object. I want it to move one click at a time one question at a time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.