黑馬程序員——objective-c數組的四種遍歷方法總結——黑馬 ios 技術博客

------Java培訓、Android培訓、iOS培訓、.Net培訓、期待與您交流! -------


摘要 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;
}

結果:


發佈了0 篇原創文章 · 獲贊 1 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章