我在尝试对一组自定义对象进行排序时遇到问题。看起来好像我的数组甚至没有命中排序代码,而只是简单地返回了数组本身。
我有以下设置:
SearchResult : NSObject
--
Document : SearchResult
Tag : SearchResult
Folder : SearchResult
我的代码以SearchResult
s 形式获得返回,然后尝试将它们与实现name
中定义的键进行比较SearchResult
。
-(void) parseFolderContents:(NSDictionary *) data
{
NSMutableArray *searchResults = [[NSMutableArray alloc] init];
NSMutableArray *documents = [[NSMutableArray alloc] init];
NSMutableArray *folders = [[NSMutableArray alloc] init];
NSMutableArray *tags = [[NSMutableArray alloc] init];
NSArray *results = [data objectForKey:@"items"];
for (int i = 0; i < [results count]; i++)
{
SearchResult *result = (SearchResult *)[KTParser parseSearchResult:[results objectAtIndex:i]];
if ([result.type isEqualToString:@"document"]){
[documents addObject:result];
}
else if ([result.type isEqualToString:@"folder"])
{
[folders addObject:result];
}
else if ([result.type isEqualToString:@"tag"])
{
[tags addObject:result];
}
}
if ([documents count] > 0)
[searchResults addObject:documents];
if ([folders count] > 0)
[searchResults addObject:folders];
if ([tags count] > 0)
[searchResults addObject:tags];
....
这就是用来填充数组的代码,没什么特别的。我已经尝试了这些方法中的每一种来比较数组。没有一个工作。有谁知道我要去哪里错了?
第一次尝试:
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name"
ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedResults;
sortedResults = [searchResults sortedArrayUsingDescriptors:sortDescriptors];
第二次尝试:
NSArray *sortedResults;
sortedResults = [searchResults sortedArrayUsingSelector:@selector(compare:)];
(implementing custom compare method on SearchResult/Document.m)
- (NSComparisonResult)compare:(SearchResult *)otherResult{
return [self.name compare:otherResult.name];
}
第三次尝试:
sortedResults = (NSMutableArray *)[searchResults sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(caseInsensitiveCompare:)]]];
第四次尝试我尝试使用块。我什至尝试输入代码来操纵它的排序,但这也不起作用。返回的数组与原始数组完全相同:
sortedArray = [searchResults sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
if ([(SearchResult *)a itemId] < 20000 )
return NSOrderedAscending;
else
return NSOrderedDescending;
}];
有人有想法么?