【发布时间】: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 == 10和index == 0在这种情况下,您的nextIndex将尝试(0-1)%10 == (-1)%10 == 9并且不会进入if (nextIndex == -1)循环
标签: ios objective-c cocoa-touch cocoa loops