我正在寻找在NSArray上迭代的标准习语。我的代码需要适合OS X 10.4+。


当前回答

这样做:

for (id object in array) 
{
        // statement
}

其他回答

这样做:

for (id object in array) 
{
        // statement
}

适用于OS X 10.4。X和之前:

 int i;
 for (i = 0; i < [myArray count]; i++) {
   id myArrayElement = [myArray objectAtIndex:i];
   ...do something useful with myArrayElement
 }

适用于OS X 10.5。x(或iPhone)及其他版本:

for (id myArrayElement in myArray) {
   ...do something useful with myArrayElement
}

这三种方法是:

        //NSArray
    NSArray *arrData = @[@1,@2,@3,@4];

    // 1.Classical
    for (int i=0; i< [arrData count]; i++){
        NSLog(@"[%d]:%@",i,arrData[i]);
    }

    // 2.Fast iteration
    for (id element in arrData){
        NSLog(@"%@",element);
    }

    // 3.Blocks
    [arrData enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
         NSLog(@"[%lu]:%@",idx,obj);
         // Set stop to YES in case you want to break the iteration
    }];

三是最快的执行方式。有了自动补全功能,就不用写迭代信封了。

下面是如何声明一个字符串数组并遍历它们:

NSArray *langs = @[@"es", @"en", @"pt", @"it", @"fr"];

for (int i = 0; i < [langs count]; i++) {
  NSString *lang = (NSString*) [langs objectAtIndex:i];
  NSLog(@"%@, ",lang);
}

为迅速

let arrayNumbers = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

// 1
for (index, value) in arrayNumbers.enumerated() {
    print(index, value)
    //... do somthing with array value and index
}


//2
for value in arrayNumbers {
    print(value)
    //... do somthing with array value
}