比较两个数组的问题

时间:2011-09-09 07:13:54

标签: iphone objective-c ios

我在Objective C中有一个循环,我比较了同一个数组的两个索引但是比较不起作用,没有编译错误。变量iMinor始终为零,arrayDistancias不为空:

NSMutableArray *arrayDistancias = [NSMutableArray array];


NSNumber *lat1 = [NSNumber numberWithFloat:39.0025];
NSNumber *lat2 = [NSNumber numberWithFloat:40.2710];
NSNumber *lat3 = [NSNumber numberWithFloat:38.5316];
NSNumber *lat4 = [NSNumber numberWithFloat:27.4529];
NSNumber *lng1 = [NSNumber numberWithFloat:-1.5139];
NSNumber *lng2 = [NSNumber numberWithFloat:-3.4327];
NSNumber *lng3 = [NSNumber numberWithFloat:-7.0029];
NSNumber *lng4 = [NSNumber numberWithFloat:-15.3432];


//for (NSInteger i = 0; i < 40; i++)
[arrayDistancias addObject:[NSNumber numberWithInteger:[self calcularDistancia:latitudaqui :lat1 :longitudaqui :lng1]]];
[arrayDistancias addObject:[NSNumber numberWithInteger:[self calcularDistancia:latitudaqui :lat2 :longitudaqui :lng2]]];
[arrayDistancias addObject:[NSNumber numberWithInteger:[self calcularDistancia:latitudaqui :lat3 :longitudaqui :lng3]]];
[arrayDistancias addObject:[NSNumber numberWithInteger:[self calcularDistancia:latitudaqui :lat4 :longitudaqui :lng4]]];


int iMinor = 0;
for (int i = 0; i < [arrayDistancias count]; i++) {

        if([arrayDistancias objectAtIndex: i] < [arrayDistancias objectAtIndex: iMinor]){
            iMinor = i;
          }              


     }

提前致谢

1 个答案:

答案 0 :(得分:2)

[arrayDistances objectAtIndex: i]返回NSNumber对象,而不是整数值。为了获取整数值,请在返回的对象上使用intValue方法。所以,你应该比较一下。

if ([[arrayDistances objectAtIndex: i] intValue] < 
   [[arrayDistances objectAtIndex: iMinor] intValue]) {