Josue Espinosa
Josue Espinosa

Reputation: 5089

Looping through array forwards and backwards?

I'm currently testing out looping through an array of objects.

The current object is presented in a ViewController with next and previous buttons. When next is pressed, the next object in the array should be presented in the view controller. If it is the last object, it should go to the first object in the array. When previous is pressed, it should display the previous object to the current object in the array. If it reaches the first object, it should go to the last object in the array. However, only the next button works, the previous button gets stuck on the first object and I don't know why. The next button works perfectly. Any ideas?

- (void)changeObject:(id)sender{

    NSUInteger index = [self.objectArray indexOfObject:self.currentObject];

    UIBarButtonItem *button = (UIBarButtonItem *)sender;
    NSUInteger nextIndex;

    if([button.title isEqualToString:@"Next Object"]){
        nextIndex = (index + 1) % self.objectArray.count;
    }
    else{
        // Previous Object
        NSLog(@"Previous Object");
        nextIndex = (index - 1) % self.objectArray.count;

        if (nextIndex == -1) {
            nextIndex = self.objectArray.count - 1;
        }
    }

    index = nextIndex;
    self.currentObject = [self.objectArray objectAtIndex:index];

    self.navigationItem.title = [NSString stringWithFormat:@"%@'s Values", self.currentObject.name];

}

EDIT: what I ended up doing was the following:

- (void)changeObject:(id)sender{

    NSInteger index = [self.objectArray indexOfObject:self.currentObject];

    UIBarButtonItem *button = (UIBarButtonItem *)sender;

    if([button.title isEqualToString:@"Next Object"]){
        index++;
        if (index >= self.objectsArray.count){
             index = 0;
        }
    }
    else{
        index--;
        if (index < 0){
             index = self.objectsArray.count - 1;
        }
    }

    self.currentObject = [self.objectArray objectAtIndex:index];

    self.navigationItem.title = [NSString stringWithFormat:@"%@'s Values", self.currentObject.name];

}

Upvotes: 0

Views: 108

Answers (1)

Logan
Logan

Reputation: 53112

Try something like this:

- (void)changeObject:(id)sender{

    NSInteger index = [self.objectArray indexOfObject:self.currentObject];

    UIBarButtonItem *button = (UIBarButtonItem *)sender;

    if([button.title isEqualToString:@"Next Object"]){
        index++;
        if (index >= self.objectsArray.count) index = 0;
    }
    else{
        index--;
        if (index < 0) index = self.objectsArray.count - 1;
    }

    self.currentObject = [self.objectArray objectAtIndex:index];

    self.navigationItem.title = [NSString stringWithFormat:@"%@'s Values", self.currentObject.name];

}

Upvotes: 2

Related Questions