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;
}
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的java enumerator_NSEnumerator使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 微信html5电子相册,维本- 电
- 下一篇: gettype拿不到值_王者荣耀:被低估