在switch块中使用objectAtIndex方法

时间:2014-09-02 16:39:47

标签: ios objective-c arrays xcode latitude-longitude

我的阵列中有一系列的晶格和经度,

NSArray *anArrayOfFloatObjects = [NSArray arrayWithObjects:
                                  [NSNumber numberWithDouble:pinLocation1.latitude],
                                  [NSNumber numberWithDouble:pinLocation1.longitude],
                                  [NSNumber numberWithDouble:pinLocation2.latitude],
                                  [NSNumber numberWithDouble:pinLocation2.longitude],
                                  [NSNumber numberWithDouble:pinLocation3.latitude],
                                  [NSNumber numberWithDouble:pinLocation3.longitude],
                                  nil];

我想要做的是使用switch语句来遍历数组(即objectAtIndex ..)

   switch (self.anArrayOfFloatObjects objectAtIndex:) {
        case :0
        //switch the pin color to red
            break;
        case :2
        //switch pin color to green
            break;
        default:
            break;
    }

这显然不起作用。有没有人知道其他任何方式?

3 个答案:

答案 0 :(得分:2)

我相信你要找的是

[anArrayOfFloatObjects indexOfObject:number]

也许这段代码会有所帮助:

NSArray *anArrayOfFloatObjects; //Your array

for (NSNumber *number in anArrayOfFloatObjects) {

    switch ([anArrayOfFloatObjects indexOfObject:number]) {
        case :0
            //switch the pin color to red
            break;
        case :2
            //switch pin color to green
            break;
        default:
            break;
    }
}

编辑:

关注@MikeS评论你可以这样做:

for (int index = 0; index < [anArrayOfFloatObjects count]; index++) {
    switch (index) {
        case :0
            //switch the pin color to red
            break;
        case :2
            //switch pin color to green
            break;
        default:
            break;
    }
}

避免调用[anArrayOfFloatObjects indexOfObject:number]

的需要

答案 1 :(得分:2)

尝试快速枚举

for(id item in anArrayOfFloatObjects){
    NSLog(@"%@", item);
}

答案 2 :(得分:1)

您还可以查看NSArray的enumerateObjectsUsingBlock

[yourArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NSLog(@"Index: %ld - Object: %@", idx, obj);
}];