【问题标题】:Looping through array forwards and backwards?向前和向后循环遍历数组?
【发布时间】:2014-04-05 22:49:54
【问题描述】:

我目前正在测试循环遍历一组对象。

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

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

}

【问题讨论】:

  • 你不想在递减时取模数。将nextIndex = (index - 1) % self.objectArray.count; 更改为nextIndex = (index - 1);
  • else 部分中的模数函数把事情搞砸了。说self.objectArray.count == 10index == 0 在这种情况下,您的nextIndex 将尝试(0-1)%10 == (-1)%10 == 9 并且不会进入if (nextIndex == -1) 循环

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


【解决方案1】:

试试这样的:

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

}

【讨论】:

  • OP 想要这个在 else 中,仔细阅读帖子:if (index
  • 我想你一定是在我更新之前写的:) 已经修复了。
  • @davidf2281 为什么?我没看到。
  • 无符号表达式 if(index<=-1) 会工作吗?我试过了,没有任何反应。下一个功能虽然完美:)
  • 您可以将NSUInteger 更改为NSInteger,它会起作用。
猜你喜欢
  • 1970-01-01
  • 2019-08-10
  • 1970-01-01
  • 2018-03-09
  • 1970-01-01
  • 2012-01-22
  • 1970-01-01
  • 2012-09-12
  • 1970-01-01
相关资源
最近更新 更多