Objective-C中快速枚举和数组排序

快速枚举

for (<#type *object#> in <#collection#>){

}

object是遍历得到的元素对象,collection是集合类型的对象:数组,字典,集合.

数组枚举得到数组中的元素对象.

字典枚举得到字典中的key值.

集合枚举得到集合中的元素对象.

 1 // 数组
 2 NSArray *arr = [NSArray arrayWithObjects:@"iPhone", @"demaxiya", @"翡翠梦境", @"龙之谷", @"bloodStrike", dic, nil];
 3     // 数组快速遍历 得到每个元素
 4     for (NSString *temp in arr) {
 5         NSLog(@"temp %@", temp);
 6     }
 7 // 字典
 8 NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"zhangsan", @"name", @"male", @"sex", @"18", @"age", nil];
 9     for (NSString *temp in dic) {
10     NSLog(@"temp %@", temp);
11     NSLog(@"%@ = %@", temp, [dic objectForKey:temp]);     
12    }

数组排序

数组默认排序

不可变数组:[array sortedArrayUsingSelector:<#(SEL)#>].

1 NSArray *arr = [NSArray arrayWithObjects:@"1", @"4", @"2", @"3", nil];
2 NSLog(@"arr: %@", arr);
3 // 排序方法
4 // SEL        方法类型
5 // @seletor() 方法选择器
6 SEL method = @selector(compare:);
7 NSArray *arr1 = [arr sortedArrayUsingSelector:method];
8 NSLog(@"arr %@", arr1);

可变数组:[mutableArray sortUsingSelector:<#(SEL)#>].

1 // 可变数组排序
2     NSMutableArray *mArr = [NSMutableArray arrayWithArray:arr];
3     NSLog(@"arr: %@", arr);
4     [mArr sortUsingSelector:@selector(compare:)];
5     NSLog(@"arr: %@", mArr);
6     [mArr addObject:@"app"];
7     [mArr addObject:@"store"];
8     [mArr sortUsingSelector:@selector(compare:)];
9     NSLog(@"arr: %@", mArr);

 

posted @ 2015-03-01 14:37  苏叶  阅读(275)  评论(0编辑  收藏  举报