/**
* 数组遍历的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...