OC数组的四种的遍历方法

摘要  objective-c 语言 数组遍历的4种方式:1、普通for循环;2、快速for循环;3、特性block方法;4、枚举方法。

Blog类: 
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#import "Blog.h"
@implementation Blog
 
+(Blog *)blog{
     Blog * blog = [[Blog alloc] init];
     return blog;
}
 
-(Blog *)setBlogTitle:(NSString *)title andContent:(NSString *)content{
     _title = title;
     _content = content;
     return self;
}
 
-(NSString *)description{
     return [NSString stringWithFormat:@ "blog : title is \"%@\" , and content is \"%@\"" , _title,_content ];
}
 
-( void )dealloc{
     NSLog(@ "%@被销毁了" ,self.title);
}
@end

主函数: 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#pragma mark Array数组的四种遍历方法
void testArray(){
     Blog *blog1 = [[Blog blog] setBlogTitle:@ "Love" andContent:@ "I love you" ];
     Blog *blog2 = [[Blog blog] setBlogTitle:@ "Friendship" andContent:@ "you are my best friend" ];
     NSArray *array = [NSArray arrayWithObjects:@ "hello" ,@ "world" ,blog1,blog2, nil];
     
     //第一种遍历:普通for循环
     long int count = [array count];
     for ( int i = 0 ; i < count; i++) {
         NSLog(@ "1遍历array: %zi-->%@" ,i,[array objectAtIndex:i]);
     }
     
     //第二种遍历:快速for循环,需要有外变量i
     int i = 0;
     for (id obj in array) {
         NSLog(@ "2遍历array:%zi-->%@" ,i,[array objectAtIndex:i]);
         i++;
     }
     
     //第三种遍历:OC自带方法enumerateObjectsUsingBlock:
     
     //默认为正序遍历
     [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
         NSLog(@ "3遍历array:%zi-->%@" ,idx,obj);
     }];
     //NSEnumerationReverse参数为倒序遍历
     [array enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
         NSLog(@ "4倒序遍历array:%zi-->%@" ,idx,obj);
     }];
     
     //第四种遍历:利用枚举
     NSEnumerator *en = [array objectEnumerator];
     id obj;
     int j = 0 ;
     while (obj = [en nextObject]) {
         NSLog(@ "5遍历array:%d-->%@" ,j,obj);
         j++;
     }
}
int main( int argc, const char * argv[])
{
     @autoreleasepool {
         testArray();
     }
     return 0;
}

结果: 



  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值