您的位置:首页 > 其它

NSArray,NSSet,NSDictionary的遍历,基本使用集锦

2013-11-29 19:36 246 查看
NSArray *array = [NSArray arrayWithObjects:@"zhangsan",@"lisi",@"wangwu",@"zhaoda", nil];
//如何把 数组元素 一一取出?
//方法一:for循环
for (int i = 0; i < [array count]; i++) {
NSString *obj = [array objectAtIndex:i];
NSLog(@"%@",obj);
}
NSLog(@"----------");
//方法二:使用枚举器NSEnumerator
NSEnumerator *enumerator = [array reverseObjectEnumerator];
NSString *obj = nil;
while (obj = [enumerator nextObject]) {
NSLog(@"obj = %@",obj);
}
NSLog(@"----------");

//方法三:快速枚举 forin
for (NSString *obj in array) {
NSLog(@"%@",obj);
}
NSLog(@"----------");
//方法四:使用专业的枚举方式(blocks等)
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(@"!!!%@ %lu",obj,idx);
if(idx == 1)
{
*stop = YES;
}
}];

NSLog(@"#########");

//字典四种方法同上!
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"cui",@"name",@"18",@"age",@"nan",@"gender", nil];
//如何把 字典元素 一一取出?//字典没有下标概念 只能靠key区分对象
NSArray *allKeys = [dic allKeys];
NSArray *allValue = [dic allValues];
for(int i = 0;i < [dic count];i++){
NSString *key = [allKeys objectAtIndex:i];
//NSString *obj =[allValue objectAtIndex:i];
NSString *obj = [dic objectForKey:key];
NSLog(@"key = %@ obj = %@",key,obj);
}

NSEnumerator *en = [dic keyEnumerator];
NSString *key = nil;
while (key = [en nextObject]) {
NSLog(@"%@ = %@",key,[dic objectForKey:key]);
}
for (NSString *key in dic) {
NSLog(@"-%@--%@",key,[dic objectForKey:key]);
}

NSLog(@"++++++++++++");
NSSet *set = [NSSet setWithObjects:@"guangmu",@"duowen",@"zengchang",@"chiguo", nil];
//如何把 集合元素 一一取出?
NSArray *objects = [set allObjects];
for (int i = 0; i < [objects count]; i++) {
NSLog(@"%@",[objects objectAtIndex:i]);
}

NSEnumerator *e = [set objectEnumerator];
NSString *o = nil;
while (o = [e nextObject]) {
NSLog(@"%@",o);
}
for (NSString *obj in set) {
NSLog(@"=%@",obj);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: