数组遍历:
索引遍历
枚举遍历:
- NSEnumerator* enumerator = [array objectEnumerator];
- id e = nil;
- while (e = [enumerator nextObject])
- {
- NSLog(@"e = %@", e);
- }
代码块遍历:
- // 示例1:枚举遍历
- [array enumerateObjectsUsingBlock:^ (id obj, NSUInteger idx, BOOLBOOL *stop){
- NSLog(@"obj = %@", obj);
- }];
- // 示例2:枚举遍历,遇到符合条件的元素(obj=array[idx])即退出遍历。
- [array enumerateObjectsUsingBlock:^ (id obj, NSUInteger idx, BOOLBOOL *stop){
- if ([obj isEqualToString:@"e3"]) {
- *stop = YES; // 中止遍历, break
- } else {
- *stop = NO; // 继续遍历,continue
- }
- }];
数组排序:
循环排序
代码块排序:
NSArray *array = @[@12,@23,@8];
NSComparator sortBlock = ^(id string1,id string2){
// return [string1 compare:string2];
if ([string1 floatValue]<[string2 floatValue]) {
return NSOrderedAscending;
}else if ([string1 floatValue]==[string2 floatValue]){
return NSOrderedSame;
}else{
return NSOrderedDescending;
}
};
NSArray *sortArray = [array sortedArrayUsingComparator:sortBlock];
NSLog(@"%@",sortArray);
}
数组逆序:
遍历逆序
方法逆序:
[[array reverseObjectEnumerator] allObjects];