我正在使用以下代码尝试将对象放入数组中。我需要该数组中特定数量的对象 - 另一个数组的计数(即 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/