1、字典的遍历 NSDictionary *dict = @{@"name": @"luoguankun",@"address":@"北京"}; //通过for循环遍历NSDictionary,不推荐 NSArray *keys = [dict allKeys]; for (int i = 0; i < keys.count ; i++) { NSString *value = [dict objectForKey:keys[i]]; NSLog(@"%@---%@",keys[i],value); } //推荐使用这种遍历方式,通过block遍历集合 [dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { NSLog(@"%@-%@",key,obj); //打印一次就停止 *stop = YES; }]; 2、数组的遍历 for循环遍历 NSArray *array1 = @[@"a",@"b",@"c",@"d",@"f",@"g"]; //普通的for循环 for(int i = 0; i < array.count; i++) { } id obj 代表着集合中的每一个元素 for(id obj in array1) { //找出obj元素在数组中的位置 unsigned long i = [array1 indexOfObject:obj]; NSLog(@"%ld=%@",i,obj); } [array1 enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) { NSLog(@"%ld = %@", idx,obj); if(idx == 2) { *stop = YES; } } ];
时间: 2024-10-11 00:23:32