/**
* 数组遍历的4种方法:1.for;2.快速for;3.特性block;4.枚举方法
*/
void testTraverse(){
NSLog(@"-----------------testTraverse-------------");
NSArray *array = [NSArray arrayWithObjects:@1,@2,@3,@4,@5, nil];
// 第一种,for
NSUInteger count = [array count];
for (int i = 0; i < count; i++) {
NSLog(@"1遍历array:%zi-->%@", i, [array objectAtIndex: i]);
}
NSLog(@"-");
// 第二种
int i = 0;
// array里面放的是对象,基本类型被转为NSNumber
for (NSNumber *value in array) {
NSLog(@"2遍历array:%zi-->%@", i, value);
i++;
}
NSLog(@"-");
// 第三种,OC自带方法enumerateObjectsUsingBlock:
[array enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop){
NSLog(@"3遍历array:%zi-->%@", idx, obj);
}];
[array enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id obj, NSUInteger idx, BOOL *stop){
NSLog(@"3倒序遍历array:%zi-->%@", idx, obj);
}];
NSLog(@"-");
// 第四种,枚举
NSEnumerator *en = [array objectEnumerator];
id obj;
int j = 0;
while (obj = [en nextObject]) {
NSLog(@"4遍历array:%zi-->%@", j, obj);
j++;
}
NSLog(@"-字典遍历-");
// 字典遍历
NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:[[Person alloc] initWithName: @"xuzhiming" andAge:10], @0, nil];
// 添加数据
[dictionary setObject:[[Person alloc] initWithName:@"longma" andAge:30] forKey:@1];
//快速枚举遍历所有KEY的值
NSEnumerator *enKey = [dictionary keyEnumerator];
id key;
while (key = [enKey nextObject]) {
//通过KEY找到value
NSLog(@"字典遍历:key: %@ value: %@", key, [dictionary objectForKey:key]);
}
//快速枚举遍历所有Value的值
NSEnumerator *enValue = [dictionary objectEnumerator];
id value;
while (value = [enValue nextObject]) {
NSLog(@"字典遍历对象:value: %@", value);
}
}
OC学习之集合遍历
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 一 、遍历 For 循环遍历 NSEnumerator 枚举器遍历 数组,字典,集合都有一个枚举器方法,返回的是枚...
- A ------ >遍历概念 1、集合 ( collection ) OC 中提供的容器 : 数组,字典,集合 2...