通过阵列向前和向后循环?

时间:2014-04-05 22:49:54

标签: ios objective-c cocoa-touch cocoa loops

我目前正在通过一系列对象测试循环。

当前对象显示在带有下一个和上一个按钮的ViewController中。按下next时,应在视图控制器中显示数组中的下一个对象。如果它是最后一个对象,它应该转到数组中的第一个对象。按下previous时,它应该将前一个对象显示到数组中的当前对象。如果它到达第一个对象,它应该转到数组中的最后一个对象。但是,只有下一个按钮有效,前一个按钮卡在第一个对象上,我不知道为什么。下一个按钮完美运行。有什么想法吗?

- (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];

}

编辑:我最终做的是以下内容:

- (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];

}

1 个答案:

答案 0 :(得分:2)

尝试这样的事情:

- (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];

}
相关问题