4

Consider a loop. I am also interested by fast enumerations. So, it could be

  • either a for(id obj in objects)
  • or a [objects enumerate... ]

I want to know if there is a classical or nice way (in Objective-C) to make a distinction between the first element of the loop and the others. Of course, if there is only a nice way to distinguish the last elements from the others, I am also interested.

Is there a classical or nice way to apply different instructions to the first or last element of a loop?

4

5 回答 5

5

使用经典for循环最简单,但由于您想要快速枚举,您需要自己的计数器:

NSUInteger index = 0;
NSUInteger count = objects.count;
for (id obj in objects) {
    if (index == 0) {
        // first
    } else if (index == count - 1) {
        // last
    } else {
        // all others
    }

    index++;
}

如果objectsNSArray,你可以这样做:

[objects enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    if (idx == 0) {
        // first
    } else if (idx == objects.count - 1) {
        // last
    } else {
        // all others
    }
}];
于 2013-10-15T17:41:11.900 回答
1

不知道是什么意思,所以这是我的想法:

[array.firstObject doSomethingWithFirst]; // iOS 7 SDK or custom category

NSRange range = NSMakeRange(1, array.count - 2); //TODO: Check for short arrays.
for (id object in [array subarrayWithRange:range]) {
    [object doSomething];
}

[array.lastObject doSomethingWithLast];

它做你想做的事,你不必费心计算索引,使用快速枚举,它是可读的(第一个和最后一个)。唯一奇怪的是这NSRange部分。

你可以认为这很好

于 2013-10-15T21:03:57.990 回答
0

Even i would recommend to use these NSArray method :-

 - (void)enumerateObjectsUsingBlock:(void (^)
   (id obj, NSUInteger idx, BOOL *stop))block
于 2013-10-15T17:57:44.573 回答
0

如果您使用 FOR 的通用语句,您可以这样做:

for (int i = 0; i < [myArray count]; i++)
{
    if(i == 0)
        NSLog("First");

    if(i == [myArray count] - 1)
        NSLog("Last");

    //rest of your code
}
于 2013-10-15T17:38:59.307 回答
0

请记住, enumerateObjectsUsingBlock 不保证以有序方式循环。您可能正在寻找的经典示例:

const NSInteger sizeOfArray = 10;
NSInteger numbers[sizeOfArray] = {10,20,30,40,50,60,70,80,90,100};

NSInteger i = 0;

do {
    switch (i) {
        case 0:
            NSLog(@"First");
            break;
        case sizeOfArray:
            NSLog(@"Last");
            break;
        default:
            NSLog(@"All others");
            break;
    }
    NSLog(@"Number = %i", numbers[i++]);
}while (i < sizeOfArray);
于 2013-10-15T20:21:48.783 回答