objective-c - For 语句每次都漏掉最后一个对象

标签 objective-c ios for-loop

我正在使用以下代码尝试将对象放入数组中。我需要该数组中特定数量的对象 - 另一个数组的计数(即 36)。

NSArray *sortedKeys = [[self.titlearray objectForKey:@"Title"] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
[self.titlearray setObject:sortedKeys forKey:@"Title"];

NSLog(@"SORTED KEYS COUNT: %i", sortedKeys.count);

for (NSObject *string in sortedKeys) {

    NSLog(@"Adding object number %i", [sortedKeys indexOfObject:string]);

    NSString *object = [[self.titlearray objectForKey:@"Title"] objectAtIndex:[sortedKeys indexOfObject:string]];

    NSArray *latlong = [[self.locationarray objectAtIndex:[[self.titlearray objectForKey:@"Title"] indexOfObject:object]] componentsSeparatedByString:@", "];
    CLLocation *firstLocation = [[CLLocation alloc] initWithLatitude:[[latlong objectAtIndex:0] doubleValue] longitude:[[latlong objectAtIndex:1] doubleValue]];
    CLLocation *secondLocation = [[CLLocation alloc] initWithLatitude:self.map.userLocation.coordinate.latitude longitude:self.map.userLocation.coordinate.longitude];
    CLLocationDistance distance = [secondLocation distanceFromLocation:firstLocation];
    float value = distance / 1000;
    NSString *distancevalue = [NSString stringWithFormat:@"%.2f", value];

    if(self.distances.count < [sortedKeys indexOfObject:object])
    [self.distances addObject:distancevalue];

    else if([sortedKeys indexOfObject:object] < self.distances.count && [self.distances objectAtIndex:[sortedKeys indexOfObject:object]])
    [self.distances replaceObjectAtIndex:[sortedKeys indexOfObject:object] withObject:distancevalue];

}

第一个 NSLog 应该显示“36”,但是当调用 for 语句时,没有出现“Adding object number 36”的日志。它只上升到 35。这很奇怪,我不确定为什么会这样。

最佳答案

Array 的起始索引从0 到 n 条记录

因此它显示完美的记录数但是当迭代时它从 0 开始到 n 条记录。

你有 36 条记录,但当迭代时它从 0 到 35 开始。

关于objective-c - For 语句每次都漏掉最后一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12702738/

相关文章:

java - 在 for 循环内的 if that 内包含 2 个 for 循环的代码的复杂性是多少

Javascript Titanium,循环标签仅显示数组中的最后一个数据

iphone - 阻止 UISearchDisplayController 放弃第一响应者键盘

ios - AFNetworking "Undefined symbols for architecture i386"错误

objective-c - 带有 clang 和 gnustep 的 Objective-C 中的简单 Hello World 无法编译

ios - 在 iOS 中访问 GCD block 中的 self

ios - 从工作日获取日期

ios - 如何正确使用 Bolts Framework 代码以及 Parse 和 Facebook?

c++ - 为什么我从这个循环中得到这个输出?

objective-c - NSWindow 缩放 "into view"(先很小,然后缩放到正常大小)