您的位置:首页 > 移动开发 > Objective-C

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

2015-03-01 14:37 393 查看
快速枚举

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

}

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

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

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

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

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


数组排序

数组默认排序

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

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


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

// 可变数组排序
NSMutableArray *mArr = [NSMutableArray arrayWithArray:arr];
NSLog(@"arr: %@", arr);
[mArr sortUsingSelector:@selector(compare:)];
NSLog(@"arr: %@", mArr);
[mArr addObject:@"app"];
[mArr addObject:@"store"];
[mArr sortUsingSelector:@selector(compare:)];
NSLog(@"arr: %@", mArr);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: