This Question have 2 answers right now.

Objective-C Loop through an array with a button?

Question!

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;
   }
}
By : J.Garcia


Answers

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.



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

By : Jecky


Video about Objective-C Loop through an array with a button?