For traversal of collection elements (such as nsarray), OC is similar to Java. But there are also differences. Let's take a look at all the methods for traversing the set elements:
1. Index Traversal
Similar to traversing a set by array subscript
1 NSArray *array;2 array = [NSArray arrayWithObjects :@"one",@"two",@"three",nil];3 for (int i = 0; i<[array count]; i++) {4 NSLog([array objectAtIndex:i]);5 }
2. traverse the set through enumeration
1 NSArray *array; 2 array = [NSArray arrayWithObjects :@"one",@"two",@"three",nil]; 3 NSEnumerator *enumlator; 4 enumlator = [array objectEnumerator]; 5 NSString *string; 6 while (string = [enumlator nextObject]) { 7 { 8 NSLog(string); 9 }10 }
3. Below is a method that I often use in Java to quickly traverse
NSArray *array; array = [NSArray arrayWithObjects :@"one",@"two",@"three",nil]; for (NSString *string in array) { { NSLog(string); } }
However, this fast traversal is not always usable. It cannot be used on the tiger (Mac OS X 10.4) system. If you need to support the tiger System
Use nsenumerator. Use the first method when you really need to obtain a fixed underlying element.