[英]Sort Object inside NSArray?
I have an object, as below 我有一个对象,如下
#import <Foundation/Foundation.h>
@interface CountriesDAO : NSObject
@property (nonatomic, retain) NSString * countryname;
@end
#import "CountriesDAO.h"
@implementation CountriesDAO
@synthesize countryname;
@end
I have saved this in Array within appDelegate. 我已经将其保存在appDelegate的Array中。
@property (nonatomic, retain) NSArray *countriesArray;
@synthesize countriesArray;
In another controller, I fetch it like 在另一个控制器中,我像
NSArray *countriesArray = appDelegate.countriesArray; It works fine and I get array.
As I try to sort it by this way. 当我尝试通过这种方式对其进行排序时。
NSArray *countriesArray1 = appDelegate.countriesArray;
NSSortDescriptor *valueDescriptor = [[NSSortDescriptor alloc] initWithKey:@"countryname" ascending:YES];
NSArray * descriptors = [NSArray arrayWithObject:valueDescriptor];
countriesArray = [countriesArray1 sortedArrayUsingDescriptors:descriptors];
I get error 我得到错误
[__NSCFType count]: unrecognized selector sent to instance 0xa83b4d0
2013-11-01 13:21:08.882 ECP[13597:c07] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFType count]: unrecognized selector sent to instance 0xa83b4d0'
Here countriesArray is defined as 这里countryArray被定义为
@property (nonatomic, retain) NSArray *countriesArray;
您也可以尝试...
[countriesArray1 sortUsingSelector:@selector(compare:)];
I did it like this and it worked for me. 我是这样做的,对我有用。
countriesArray = [[NSMutableArray alloc] init];
for (CountriesDAO *info in appDelegate.countriesArray) {
[countriesArray addObject:info.countryname];
}
[countriesArray sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
Should work 应该管用
NSMutableArray *sortedArray = [appDelegate.countriesArray mutableCopy];
[sortedArray sortUsingComparator:^NSComparisonResult(CountriesDAO *object1,
CountriesDAO *object2) {
return [object1.countryname caseInsensitiveCompare:object2.countryname];
}];
NSArray *sortedCountriesArray = [sortedArray copy];
If something went wrong, check the type of object1
and object2
如果出现问题,请检查
object1
和object2
的类型
Its is simple Way to sort array in iOS,it's helps to you 这是在iOS中对数组进行排序的简单方法,对您有帮助
[countriesArray sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return [ String_1 compare: String_2];
}];
// String_1, String_2 are NSString,it's contains in countriesArray
// use NSMutableArray to rearrange and change values in countriesArray
如果要排序的数组包含NSString(这是我从您的描述中得到的),则可以使用以下代码替换排序代码:
sortedArray = [countriesArray1 sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.