objective-c 语言 数组遍历的4种方式
2014-04-13 00:51
274 查看
objective-c
语言 数组遍历的4种方式:1、普通for循环;2、快速for循环;3、特性block方法;4、枚举方法。
语言 数组遍历的4种方式:1、普通for循环;2、快速for循环;3、特性block方法;4、枚举方法。
Blog类:
01 | #import "Blog.h" |
02 | @implementation Blog |
03 |
04 | +(Blog *)blog{ |
05 | Blog * blog = [[Blog alloc] init]; |
06 | return blog; |
07 | } |
08 |
09 | -(Blog *)setBlogTitle:(NSString *)title andContent:(NSString *)content{ |
10 | _title = title; |
11 | _content = content; |
12 | return self; |
13 | } |
14 |
15 | -(NSString *)description{ |
16 | return [NSString stringWithFormat:@ "blog : title is \"%@\" , and content is \"%@\"" , _title,_content ]; |
17 | } |
18 |
19 | -( void )dealloc{ |
20 | NSLog(@ "%@被销毁了" ,self.title); |
21 | } |
22 | @end |
主函数:
01 | #pragma mark Array数组的四种遍历方法 |
02 | void testArray(){ |
03 | Blog *blog1 = [[Blog blog] setBlogTitle:@ "Love" andContent:@ "I love you" ]; |
04 | Blog *blog2 = [[Blog blog] setBlogTitle:@ "Friendship" andContent:@ "you are my best friend" ]; |
05 | NSArray *array = [NSArray arrayWithObjects:@ "hello" ,@ "world" ,blog1,blog2, nil]; |
06 |
07 | //第一种遍历:普通for循环 |
08 | long int count = [array count]; |
09 | for ( int i = 0 ; i < count; i++) { |
10 | NSLog(@ "1遍历array: %zi-->%@" ,i,[array objectAtIndex:i]); |
11 | } |
12 |
13 | //第二种遍历:快速for循环,需要有外变量i |
14 | int i = 0; |
15 | for (id obj in array) { |
16 | NSLog(@ "2遍历array:%zi-->%@" ,i,[array objectAtIndex:i]); |
17 | i++; |
18 | } |
19 |
20 | //第三种遍历:OC自带方法enumerateObjectsUsingBlock: |
21 |
22 | //默认为正序遍历 |
23 | [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { |
24 | NSLog(@ "3遍历array:%zi-->%@" ,idx,obj); |
25 | }]; |
26 | //NSEnumerationReverse参数为倒序遍历 |
27 | [array enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id obj, NSUInteger idx, BOOL *stop) { |
28 | NSLog(@ "4倒序遍历array:%zi-->%@" ,idx,obj); |
29 | }]; |
30 |
31 | //第四种遍历:利用枚举 |
32 | NSEnumerator *en = [array objectEnumerator]; |
33 | id obj; |
34 | int j = 0 ; |
35 | while (obj = [en nextObject]) { |
36 | NSLog(@ "5遍历array:%d-->%@" ,j,obj); |
37 | j++; |
38 | } |
39 | } |
40 | int main( int argc, const char * argv[]) |
41 | { |
42 | @autoreleasepool { |
43 | testArray(); |
44 | } |
45 | return 0; |
46 | } |
结果:
相关文章推荐
- Objective-C 声明一个C语言类型的数组和访问方式@property
- Objective-C中遍历字典、数组和集合的几种常见方式
- js中数组的4种遍历方式
- Objective-C语法之NSArray的4种遍历方式
- OC数组 NSArray的4种遍历方式
- s中数组的4种遍历方式
- 遍历java集合或数组的几种方式
- Java 4种数组复制方式的性能比较
- Java语言对对象引用的4种方式
- 不同语言中一维数组的定义方式
- awk中遍历数组的2种方式
- java8 遍历数组的几种方式
- iOS开发实用技巧—Objective-C中的各种遍历(迭代)方式
- iOS开发实用技巧—Objective-C中的各种遍历(迭代)方式
- 【C 语言】指针 与 数组 ( 指针 | 数组 | 指针运算 | 数组访问方式 | 字符串 | 指针数组 | 数组指针 | 多维数组 | 多维指针 | 数组参数 | 函数指针 | 复杂指针解读)
- 二叉树的4种遍历方式(前序、中序、后序、层次)Java版
- 遍历map的4种方式
- Map遍历的4种方式。
- php遍历数组的4种方法总结
- iOS开发中数组常用的五种遍历方式