OC-数组的遍历
不可变的
NSArray *arr= @[@"1",@"2",@"3"];
arr =[arr sortedArrayUsingSelector:@selector(compare:)];
NSLog(@"%@",arr);
arr= [arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return [obj2 compare:obj1];
}];
NSLog(@"%@",arr);
可变的
NSMutableArray *a = [NSMutableArray arrayWithObjects:@"a",@"b",@"c", nil];
[a sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
// return [obj1 compare:obj2];
return [obj2 compare:obj1];
}];
NSLog(@"%@",a);
[a sortUsingSelector:@selector(compare:)];
NSLog(@"%@",a);
// 对象的数组排序
Person *p1 =[[Person alloc] init];
p1.name=@"001";
Person *p2 =[[Person alloc] init];
p2.name=@"002";
Person *p3 =[[Person alloc] init];
p3.name=@"003";
Person *p4 =[[Person alloc] init];
p4.name=@"004";
// NSArray *arr =[NSArray arrayWithObjects:s1,s2,s3, nil];
NSArray *arr =[NSArray arrayWithObjects:p1,p2,p3, nil];
arr = [arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
//compare只能比字符串
Person *p1= obj1;
Person *p2= obj2;
return [p1.name compare:p2.name];
}];
for (Person *p in arr) {
NSLog(@"%@",p.name);
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。