Supposing NSArray has several objects which belong to two classes,
@interface FWNewsObj:NSObject
{
NSString *newsTitle;
NSDate *newsTime;
}
@end
@interface FWPhotoObj:NSObject
{
NSString *photoTitle;
NSDate *photoTime;
}
@end
I’d like to sort the NSArray with object’s title (or time). However the title variable in each class has different names.
Then How can I do the sort?
Thanks.
You have to write a custom compare method that both your classes implement. It must take one object as a parameter and return an
NSComparisonResult(NSOrderedAscending,NSOrderedDescendingorNSOrderedSame)You can then use
sortedArrayUsingSelector:with your own comparison method.Example:
In FWNewsObj:
In FWPhotoObj:
It would actually be easier to just define a title method in both classes that wraps either the photoTitle or the newsTitle. Then you can just use
NSSortDescriptorwithtitleas the key.