iphone - 需要帮助使用自定义对象对 NSMutableArray 进行排序

标签 iphone objective-c ios ipad

很抱歉用这个问题打扰你,但经过数小时的谷歌搜索和浏览,我仍然无法弄清楚,问题出在哪里。

问题是,我创建了一个 NSMutableArray,其中包含“SearchResult”类型的自定义对象。 SearchResult 类仍然非常基础:

@interface SearchResult : NSObject {

    NSString *_id;
    NSString *_title;
    NSNumber *_year;
}

@property (nonatomic, copy) NSString *id;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSNumber *year;

@end

这是代码,(坏的)魔法发生了:

if (self.sResults == nil) {
    self.sResults = [[NSMutableArray alloc] init];
}
else if ([self.sResults count] > 0){
    [self.sResults removeAllObjects];
}
//JsonConverter uses JsonTouchKit for parsing a json string
JsonConverter *_converter = [[JsonConverter alloc] init];
NSDictionary *parsedResults = [_converter getParsedObjectFromData:results];

for (NSDictionary *movieObj in [parsedResults objectForKey:@"results"]) {
    SearchResult *movie = [_converter newSearchResultObjectFromSearchJsonObject:movieObj];
    [self.sResults addObject:movie];
}
[_converter release];
//sort the results
NSSortDescriptor *desc = [[[NSSortDescriptor alloc] initWithKey:@"year" ascending:NO] autorelease];

NSArray * sortDescriptors = [NSArray arrayWithObject:desc];
[self.sResults sortUsingDescriptors:sortDescriptors];  //<-- HERE!!!
[self.tableView reloadData];

问题是,如果我只得到几个结果,例如3、一切正常,数组排序正确。但是一旦我得到更多结果,例如18,应用程序在带有“SIGABRT”和下面堆栈的标记行上崩溃。 如果我在对 gdb 命令知之甚少的情况下检查给定的地址“0x5c31470”,我会得到以下信息:

po 0x5c31470 -> 2004 //yes, thats the year it should use for sorting
whatis 0x5c31470 -> type = int

堆栈跟踪:

2011-09-13 12:30:10.352 VideoCatalogue[1294:207] -[NSCFNumber length]: unrecognized selector sent to instance 0x5c31470

2011-09-13 12:30:10.353 VideoCatalogue[1294:207] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSCFNumber length]: unrecognized selector sent to instance 0x5c31470'

有谁知道我该如何解决这个问题?非常感谢!

最佳答案

使用这种方法:NSArray Class Reference 查找以下内容的解释:sortedArrayUsingFunction:context:

关于iphone - 需要帮助使用自定义对象对 NSMutableArray 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7401109/

相关文章:

iphone - 将 NSArray 转换为 NSMutableArray

iphone - 我正在尝试使用 MWFeedParser 显示 MBProgressHUD 的进度

iphone - CGImageCreate 中的颜色失真

iphone - 识别 NSString 中的几个整数

objective-c - EffectiveRange 和 LongestEffectiveRange 之间的区别

iphone - 如何将所选 ID 与数组中的国家/地区 ID 进行比较并显示其名称而不是 ID

iphone - 如何在登录 Iphone App 后重定向到主页选项卡?

iphone - 如何将 SVN 修订号添加到 iPhone 应用程序构建?

ios - APPDelegate 中的 openURL 转换错误 NSString -> String (Swift & iOS8)

iphone - ARC 语义问题 : No visible @interface for Class declares the selector