dav*_*ryn 8 sorting iphone objective-c
所以我有一个Foo包含许多成员的自定义类:
@interface Foo : NSObject {
NSString *title;
BOOL taken;
NSDate *dateCreated;
}
Run Code Online (Sandbox Code Playgroud)
在另一个类中,我有一个NSMutableArray包含这些对象的列表.我非常想根据dateCreated属性对这个数组进行排序; 我知道我可以为此编写自己的排序器(迭代数组并根据日期重新排列)但我想知道是否有一种正确的Objective-C方法来实现这一目标?
我可以提供成员变量排序的某种排序机制会很棒.
在C++中我曾经重载<=>运算符,这允许我按对象排序,但我有一种有趣的感觉Objective-C可能提供更好的选择?
非常感谢
Paw*_*wel 15
这很简单.
首先,在您的Foo对象中,创建一个方法
- (NSComparisonResult) compareWithAnotherFoo:(Foo*) anotherFoo;
Run Code Online (Sandbox Code Playgroud)
哪个会回归
[[self dateCreated] compare:[anotherFoo dateCreated]];
Run Code Online (Sandbox Code Playgroud)
最后,调用数组
[yourArray sortUsingSelector:@selector(compareWithAnotherFoo:)];
Run Code Online (Sandbox Code Playgroud)
希望这有帮助,保罗