u Fast Enumeration

n         정의

반복문

              Objective-C 2.0 새로 추가된 기능

NSFastEnumeration 프로토콜을 지원하는 모든 컬렉션(NSArray, NSDictionary, NSSet, NSEnumerator)에서 사용가능.
직접 만든 컬렉션에서 fast enumeration 지원할려고 하면 NSFastEnumeration 프로토콜을 지원하면 된다.

// one
for ( Type newVariable in expression ) { statements }


// two
Type existingItem;
for ( existingItem in expression ) { statements }

 

n         NSArray 예제

NSArray *array = [NSArray arrayWithObjects:@"One", @"Two", @"Three", @"Four", nil];
for (NSString *element in array) {
    NSLog(@"element: %@", element);
}
// element: One
// element: Two
// element: Three
// element: Four

 

n         NSDictionary 예제

NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:

@"quattuor", @"four", @"quinque", @"five", @"sex", @"six", nil];
NSString *key;
for (key in dictionary) {
  NSLog(@"English: %@, Latin: %@", key, [dictionary valueForKey:key]);
}
// English: four, Latin: quattuor
// English: five, Latin: quinque
// English: six, Latin: sex

 

n         NSArray ? nextObject 예제

NSArray *array = [NSArray arrayWithObjects:@"One", @"Two", @"Three", @"Four", nil];
NSEnumerator *enumerator = [array reverseObjectEnumerator];
for (NSString *element in enumerator) {
    if ([element isEqualToString:@"Three"]) {
        break;
    }
}
NSString *next = [enumerator nextObject];
// next = "Two"

 

n         index를 이용한 예제

NSArray *array = /* assume this exists */;

NSUInteger index = 0;

 

for (id element in array) {

    NSLog(@"Element at index %u is: %@", index, element);

    index++;

}

 

n         아래 두가지 예제는 조건에 따라 일부 처리 요소를 제외할 수 도 있다는 것을 보여줌

NSArray *array = /* assume this exists */;

 

for (id element in array) {

    if (/* some test for element */) {

        // statements that apply only to elements passing test

    }

}

NSArray *array = /* assume this exists */;

NSUInteger index = 0;

 

for (id element in array) {

     if (index != 0) {

          NSLog(@"Element at index %u is: %@", index, element);

     }

      if (++index >= 6) {

          break;

     }

}

 

Posted by 김반장78
,