以NSArray为例。
1、for循环
NSArray *array = [NSArray arrayWithObjects:@0", @"1",@"2",nil];
int count = array.count;
for( int i = 0 ; i < count ;i ++)
{
NSLog(@"%i-%@", i, [array objectAtIndex:i]);
}
for(id obj in array)
{
NSLog(@"%@",obj);
}
2、NSEnumerator
NSEnumerator *enumerator = [array objectEnumerator];
id obj = nil;
while(obj = [enumerator nextObject]){
NSLog(@"obj=%@",obj);
}
3、
//顺序遍历 NSDictionary 同时取key和value
NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:@"value0",@"key0",@"value1",@"key1", nil];
[dic enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop)
{
NSLog(@"value for key %@ is %@ ", key, value);
if ([@"key1" isEqualToString:key])
{
*stop = YES;
}
}];
//顺序遍历 NSArray
[array enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSLog(@"%@",array[idx]);
}];
//NSEnumerationReverse 倒序遍历
//NSEnumerationConcurrent 正序遍历
[array enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSLog(@"%@",array[idx]);
}];