sort NSArray with objects
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 differ开发者_Python百科ent names.
Then How can I do the sort? Thanks.
What is instantly coming to my mind is(If I am understanding the Q correctly) :
- 1st create a dictionary, with titleNames as the keys, and value as the objects
- Sort the keys array simply
- Then create a sorted array of objects pulling them out of the dictionary, on basis of this sorted keys array
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
, NSOrderedDescending
or NSOrderedSame
)
You can then use sortedArrayUsingSelector:
with your own comparison method.
Example:
In FWNewsObj:
- (NSComparisonResult)compareTitle:(id)obj
{
NSAssert([obj isKindOfClass:[FWNewsObj class]] || [obj isKindOfClass:[FWPhotoObj class]], @"Don't know how to compare %@ to %@", self, obj);
if ([obj isKindOfClass:[FWPhotoObj class]]) {
return [newsTitle compare:[(FWPhotoObj *)obj photoTitle]];
} else {
return [newsTitle compare:[(FWNewsObj *)obj newsTitle]];
}
}
In FWPhotoObj:
- (NSComparisonResult)compareTitle:(id)obj
{
NSAssert([obj isKindOfClass:[FWNewsObj class]] || [obj isKindOfClass:[FWPhotoObj class]], @"Don't know how to compare %@ to %@", self, obj);
if ([obj isKindOfClass:[FWPhotoObj class]]) {
return [photoTitle compare:[(FWPhotoObj *)obj photoTitle]];
} else {
return [photoTitle compare:[(FWNewsObj *)obj newsTitleTitle]];
}
}
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 NSSortDescriptor
with title
as the key.
精彩评论