objective-c 语言 数组遍历的4种方式:1、普通for循环;2、快速for循环;3、特性block方法;4、枚举方法
Blog类:
```
```#import "Blog.h"
android {
buildTypes {
debug {
testCoverageEnabled = true
}
}
}
@implementation Blog
+(Blog *)blog{
Blog * blog = [[Blog alloc] init];
returnblog;
}
-(Blog *)setBlogTitle:(NSString *)title andContent:(NSString *)content{
_title = title;
_content = content;
returnself;
}
-(NSString *)description{
return[NSString stringWithFormat:@"blog : title is \"%@\" , and content is \"%@\"", _title,_content ];
}
-(void)dealloc{
NSLog(@"%@被销毁了",self.title);
}
主函数:
#pragma mark Array数组的四种遍历方法
voidtestArray(){
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循环
longintcount = [array count];
for(inti = 0 ; i < count; i++) {
NSLog(@"1遍历array: %zi-->%@",i,[array objectAtIndex:i]);
}
//第二种遍历:快速for循环,需要有外变量i
inti = 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;
intj = 0 ;
while(obj = [en nextObject]) {
NSLog(@"5遍历array:%d-->%@",j,obj);
j++;
}
}
intmain(intargc,constchar* argv[])
{
@autoreleasepool {
testArray();
}
return0;
}
```
结果: