通过选择器使用自定义比较器的 NSSortDescriptor 问题
我想使用带有自定义比较器的排序描述符
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]
initWithKey:@"object.dateTime"
ascending:YES
selector:@selector(compareObject:toObject:)];
(关键是 ManagedObject)
比较器方法:
- (NSComparisonResult)compareObject:(id)date1 toObject:(id)date2 {
NSComparisonResult comparisonResult;
// Complex comparator contents
return comparisonResult;
}
但是,我收到错误: 'NSInvalidArgumentException',原因:'-[__NSDatecompareObject:toObject:]:发送了无法识别的选择器.....
我做错了什么? 如果我在块中使用比较器,它就可以工作,但我需要它通过选择器工作。 我找不到任何关于如何通过选择器使用比较器的示例代码或清晰的文档(适用于 iOS 3.xx)。该文档讨论了与 self 进行比较,但我尝试将比较方法合并到对象中,但这也不起作用。
谁可以指出我的问题或一些示例代码以了解如何通过选择器使用它?
注意:比较器本身并不是简单的日期比较。那里还发生了很多事情。
I want to use a sortdescriptor with a custom comparator
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]
initWithKey:@"object.dateTime"
ascending:YES
selector:@selector(compareObject:toObject:)];
(the key is a ManagedObject)
Comparator method:
- (NSComparisonResult)compareObject:(id)date1 toObject:(id)date2 {
NSComparisonResult comparisonResult;
// Complex comparator contents
return comparisonResult;
}
However, I get an error:
'NSInvalidArgumentException ', reason: '-[__NSDate compareObject:toObject:]: unrecognized selector sent .....
What am I doing wrong?
The comparator works if I use it in a block, but I need it to work via a selector.
I can't find any example code or clear documentation on how to use comparators via a selector (for iOS 3.x.x). The documentation talks about comparing to self, but I've tried to incorporate the compare method in object, but that didn't work either.
Who can point me to my problem or to some example code as to how to use this via a selector?
Note: The comparator itself is not a simple date comparison. There is a lot more going on in there.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您要比较
NSDate
对象,则您传递的选择器必须是NSDate
类的一种方法,并且仅采用一个参数。来自 NSSortDescriptor 文档:
要提供您自己的排序选择器,您应该在 NSDate 上定义一个类别,并在此处放置您的自定义排序方法,例如
OR 如果您不关心 iOS 版本 OR 如果您不关心 iOS 版本 OR 4.0,您还可以使用
cmptr
作为一个块,如下所示:If you're comparing
NSDate
objects, the selector you pass has to be a method of theNSDate
class and take only one argument.From the NSSortDescriptor doc:
To provide your own sort selector you should define a category on NSDate and place your custom sort method here like
OR If you don't care about iOS versions < 4.0, you could also use
cmptr
being a block like this: