NSEnumerator
3)枚举 (NSEnumerator)
遍历数组每个索引处的对象,你可以编写一个0到[array count]的循环,而NSEnumerator用来描述这种集合迭代运算的方式。通过objectEnumerator向数组请求枚举器,如果想从后向前浏览集合,可使用reverseObjectEnumerator方法。在获得枚举器后,可以开始一个while循环,每次循环都向这个枚举器请求它的下一个对象:nextObject。nextObject返回nil值时,循环结束。示例如下: 1 // NSEnumerator示例 2 NSEnumerator *enumerator; 3 enumerator = [array objectEnumerator]; 4 id thing; 5 while (thing = [enumerator nextObject]) { 6 NSLog(@"I found %@",thing); 7 }
对于可变数组进行枚举操作时,主要不要添加或删除数组中的对象。
4)快速枚举Objective-C2.0支持快速枚举:如 1 for (NSString *string in array) 2 { 3 NSLog(@" I found %@",string); 4 } 5 6
这个循环将会遍历数组中的每个元素,并且用变量string存储每个数组值。它比枚举器语法更加简洁快捷。
NSLog(@"Hello, World!"); NSDictionary *myDic=[[NSDictionary alloc]initWithObjectsAndKeys:@"张三",@"name",@"李四",@"name", nil]; NSUInteger count = [myDic count]; NSLog(@"词典的数量为: %lu",count); NSEnumerator * myEnumerator = [myDic keyEnumerator]; for (NSObject *object in myEnumerator) { NSLog(@"遍历KEY的值: %@",object); } myEnumerator = [[myDic allValues] objectEnumerator]; NSString *value; while((value = [myEnumerator nextObject])) { NSLog(@"遍历的值: %@",value); } //通过KEY找到value NSObject *myObject = [myDic objectForKey:@"name"]; if (myObject != nil) { NSLog(@"通过KEY找到的value是: %@",myObject); } NSMutableDictionary *mydic2 = [NSMutableDictionary dictionaryWithCapacity:10]; [mydic2 setObject:@"Alex Hu" forKey:@"name"]; [mydic2 setObject:@"1388888888" forKey:@"mobile number"]; for (NSObject *object in [mydic2 objectEnumerator]) { NSLog(@"遍历的值: %@",object); } NSSet *mySet=[NSSet setWithObjects:@"A",@"B",@"C",@"D",[NSNumber numberWithInteger:123], nil]; count=[mySet count]; NSLog(@"count= %lu",count); myEnumerator=[mySet objectEnumerator]; for (NSObject *object in myEnumerator) { NSLog(@"myEnumerator value=%@",object); if ([object isEqualTo:@"A"]) { NSLog(@"找到A了"); } if ([object isEqual:@"B"]) { NSLog(@"找到B"); } } NSArray *mySetArr=[mySet allObjects]; for (NSUInteger i=0; i<[mySetArr count];i++) { NSLog(@"%lu =>%@",i,[mySetArr objectAtIndex:i]); } if ([mySet containsObject:@"D"]) { NSLog(@"集合中包含 D这个对象"); }
NSFileManager *fm=[NSFileManager defaultManager]; for(NSString *fileName in [fm enumeratorAtPath:documentsDirectory]) { if([[fileName pathExtension]isEqualToString:@"jpg"]) { } }