美文网首页
OC:数组的遍历方式

OC:数组的遍历方式

作者: JBright_Lee | 来源:发表于2016-05-07 13:45 被阅读142次

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;

}

```

结果:

相关文章

  • OC:数组的遍历方式

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

  • Objective-C 数组遍历的性能及原理

    数组的遍历,这个话题貌似没什么好探究的,该怎么遍历就怎么遍历呗!但是如果要回答这些问题:OC数组有哪几种遍历方式?...

  • Foundation框架---数组

    OC 数组特点: 可以存储不同类型的对象,oc的数组 只能存储对象 数组可以遍历,占用的内存空间是连续的. oc中...

  • Swift 4.0+ 数组遍历

    1、转换成OC数组 enumerated函数遍历 2、用enumerated()函数遍历 3、下标遍历 4、遍历数...

  • OC中快速枚举forin和for循环的区别

    在OC语言中,遍历数组时会用到四种方式: 1、普通for循环;2、快速for循环;3、特性block方式;4、枚举...

  • NSArray

    简写NSSArray *arr = @"";常规遍历如果是OC数组可以使用OC中的增强for循环来遍历诸葛取出ar...

  • OC数组遍历

    /***************************数组遍历*************************...

  • JS数组遍历的三种常用方法

    1.数组下标遍历 数组下标遍历是最常用也最普通的数组遍历方式 例如: 2.for in遍历 for in是根据数组...

  • for循环

    传统方式 1.遍历数组的传统方式 2.遍历Collection对象的传统方式 简单方式 1.遍历数组 2遍历Col...

  • JS或Jquery之遍历对象数组取出字符串用逗号拼接方式

    使用JS遍历对象数组方式一如下: 使用JS遍历数组方式二如下: 使用Jquery遍历对象数组如下:

网友评论

      本文标题:OC:数组的遍历方式

      本文链接:https://www.haomeiwen.com/subject/bbzjrttx.html