objective-c數組的四種遍歷方法總結

 objective-c 語言 數組遍歷的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 }

結果:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章