NS类 - NSArray排序一(未完待续 。。。)
(2013-05-25 21:08:08)
标签:
nsarray排序itobject-c数组排序 |
分类: Mac/IOS那些事 |
1.常用 正序排 利用数组的sortedArrayUsingComparator调用
NSComparator
NSArray *_beforeSorted = [[NSArray
alloc]initWithObjects:@"f",@"d",@"d",@"c",@"b",@"a", nil];
NSArray *_sortedArray = [_beforeSorted
sortedArrayUsingSelector:@selector(compare:)];
NSLog(@"Before Sorted:%@",_beforeSorted);
NSLog(@"After Sorted:%@",_sortedArray);
[_beforeSorted release];
output:
Before Sorted:(
f,
d,
d,
c,
b,
a
)
Sorted:(
a,
b,
c,
d,
d,
f
)
2.倒序排列(再1的基础上增加)
NSMutableArray *_reverseSorted = [[NSMutableArray alloc]init];
for (id arrayItem in [_sortedArray reverseObjectEnumerator])
{
[_reverseSorted addObject:arrayItem];
}
NSLog(@"Reverse Sorted:%@",_reverseSorted);
[_reverseSorted release];
output:
Reverse Sorted:(
f,
d,
d,
c,
b,
a
)
3 使用 sortUsingDescriptors 来实现按字典的键值来排列
利用sortUsingDescriptors调用NSSortDescriptor
NSMutableArray *_beforeSortedArray = [[NSMutableArray
alloc]init];
[_beforeSortedArray addObject:[NSDictionary
dictionaryWithObjectsAndKeys:@"aaa",@"name",@"111",@"work",
nil]];
[_beforeSortedArray addObject:[NSDictionary
dictionaryWithObjectsAndKeys:@"ccc",@"name",@"333",@"work",
nil]];
[_beforeSortedArray addObject:[NSDictionary
dictionaryWithObjectsAndKeys:@"fff",@"name",@"222",@"work",
nil]];
[_beforeSortedArray addObject:[NSDictionary
dictionaryWithObjectsAndKeys:@"bbb",@"name",@"444",@"work",
nil]];
NSSortDescriptor *_sortByName = [[NSSortDescriptor
alloc]initWithKey:@"name" ascending:YES];
NSSortDescriptor *_sortByWork = [[NSSortDescriptor
alloc]initWithKey:@"work" ascending:YES];
NSArray *_sortByNameArray = [[NSArray
alloc]initWithObjects:&_sortByName count:1];
NSArray *_sortByWorkArray = [[NSArray
alloc]initWithObjects:&_sortByWork count:1];
NSLog(@"befor Sorted:%@",_beforeSortedArray);
[_beforeSortedArray sortUsingDescriptors:_sortByNameArray];
NSLog(@"Sorted by Name:%@",_beforeSortedArray);
[_beforeSortedArray sortUsingDescriptors:_sortByWorkArray];
NSLog(@"Sorted By Work:%@",_beforeSortedArray);
output:
befor Sorted:(
{
name = aaa;
work = 111;
},
)
)
2.倒序排列(再1的基础上增加)
NSMutableArray *_reverseSorted = [[NSMutableArray alloc]init];
NSLog(@"Reverse Sorted:%@",_reverseSorted);
[_reverseSorted release];
output:
)
3
output: