podoi17 podoi17 - 1 year ago 73
Objective-C Question

Clicking through an array

i am still in the process of learning. I want to be able to click through an array of objects and this object is shown in a textlable. This is how far i got:

I am starting with the object at position 0. When a button is clicked the label says one. I am tapping the button again and the label says two and than after clicking again it says three. Can somebody help pls?

--> Edited Question:

I knew i need count++ somehow but i am not sure how to use it correctly. If i am putting it where it stands in the code right now, the label only says two. And yeah it should because it is increasing count by one so the object at its index is the "two". It only shows "two" in the label. So is there a way to make it work with if statements?

NSString *word = {@"one,two,three"};
NSArray *anArray = [word componentsSeparatedByString:@","];
int count = anArray.count;
count = 0;

if (count == 0){
_labelText.text = [NSString stringWithFormat:@"%@" , [anArray objectAtIndex:0]];

else if(count == 1){
_labelText.text = [NSString stringWithFormat:@"%@", [anArray objectAtIndex:1]];

else if (count ==2){
_labelText.text = [NSString stringWithFormat:@"%@", [anArray objectAtIndex:2]];

Answer Source

Try this:

@interface ViewController ()

@property (nonatomic, weak) IBOutlet UILabel *labelText;
@property (nonatomic, strong) NSArray *words;
@property (nonatomic, readwrite) NSInteger counter;


@implementation ViewController

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

    self.words = @[@"one", @"two", @"three"];
    self.counter = 0;

    [self updateUI];

- (IBAction)nextButton:(id)sender {
    self.counter = (self.counter + 1) % self.words.count;
    [self updateUI];

- (void)updateUI {
    self.labelText.text = self.words[self.counter];

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download