java enumerator_NSEnumerator使用

集合类(如:NSArray、NSSet、NSDictionary等)均可获取到NSEnumerator, 该类是一个抽象类,没有用来创建实例的公有接口。NSEnumerator的nextObject方法可以遍历每个集合元素,结束返回nil,通过与while结合使用可遍历集合中所有项。

例子中使用了与前例相同的Photo对象,具体定义参考 隐式循环 这一节。

#import

#import "Photo.h"

int main (int argc, const char * argv[])

{

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

//while+NSEnumerator

//定义对象的数组

NSArray *array = [NSArray arrayWithObjects:[[Photo alloc] init], [[Photo alloc] init],[[Photo alloc] init], nil];

//通过objectEnumberator获取集合的NSEnumerator

NSEnumerator *myEnumerator = [array objectEnumerator];

Photo *photo;

//nextObject遍历每一项,结束返回nil

//注意这里使用的是“=”号,所以最外面还要再添加一对()

while((photo = [myEnumerator nextObject]))

{

[photo draw];

}

[pool drain];

return 0;

}

NSSet allObjects

#import

#import "Photo.h"

int main (int argc, const char * argv[])

{

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

//NSSet allObjects

NSSet *set = [NSSet setWithObjects:[[Photo alloc] init], [[Photo alloc] init],[[Photo alloc] init], nil];

//allObjects仅能获取NSArray,需要再次调用objectEnumberator

//并且获取的数组顺序不确定。

NSEnumerator *myEnumerator = [[set allObjects] objectEnumerator];

Photo *photo;

while((photo = [myEnumerator nextObject]))

{

[photo draw];

}

[pool drain];

return 0;

}

NSDictionary allValues allKeys

#import

#import "Photo.h"

int main (int argc, const char * argv[])

{

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

//NSDictionary allValues

//NSDictionary 添加项时是value在前j,key在后的,与C#相反

NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:

[[Photo alloc] init], @"p1",

[[Photo alloc] init], @"p2",

[[Photo alloc] init], @"p3", nil];

//allValues 只能获取字典中值的数组列表,注意列表是无序的。

NSEnumerator *myEnumerator = [[dict allValues] objectEnumerator];

Photo *photo;

while((photo = [myEnumerator nextObject]))

{

[photo draw];

}

//allKeys 遍历字典中的所有key列表,然后能过objectForKey获取值。注意列表是无序的。

myEnumerator = [[dict allKeys] objectEnumerator];

NSString *key;

while((key = [myEnumerator nextObject]))

{

//objectForKey从字典中获取key对应的值

[[dict objectForKey:key] draw];

}

[pool drain];

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值