iOS排序对象数组

时间:2014-04-09 03:07:27

标签: ios sorting nsmutablearray comparator

我有一个数组,用于填充我想按日期排序的应用Feed。我已经看过这个问题(https://stackoverflow.com/a/805589/577732)但是无法让它为我的数组工作。我的课程如下,我正在创建我的对象数组,任何有关排序我的数组的帮助都将非常感激。

ftime是我想要排序的它是来自我服务器上的mysql数据库的时间戳我目前正在使用NSString存储它,但如果需要进行排序可以转换为NSDate。

ObjectArrays.h

@interface ObjectArrays : NSObject {
    //Feed
    NSString *fid;
    NSString *favatar;
    NSString *fuser;
    NSString *ftime;
    NSString *fmsg;
}

//Feed
@property (nonatomic, copy) NSString *fid, *favatar, *fuser, *ftime, *fmsg;
//Feed
+ (id)productWithType:(NSString *)fid favatar:(NSString *)favatar fuser:(NSString *)fuser ftime:(NSString *)ftime fmsg:(NSString *)fmsg;

@end

ObjectArrays.m

#import "ObjectArrays.h"

@implementation ObjectArrays

@synthesize fid, favatar, fuser, ftime, fmsg;

+ (id)productWithType:(NSString *)fid favatar:(NSString *)favatar fuser:(NSString *)fuser ftime:(NSString *)ftime fmsg:(NSString *)fmsg{
    ObjectArrays *newArray = [[self alloc] init];
    newArray.fid=fid;
    newArray.favatar=favatar;
    newArray.fuser=fuser;
    newArray.ftime=ftime;
    newArray.fmsg=fmsg;
    return newArray;
}

@end

FeedClass.m

listArray = [[NSMutableArray alloc] init];
[listArray addObject:[ObjectArrays productWithType:[object objectForKey:@"ID"] favatar:[userObject objectForKey:@"Avatar"] fuser:[NSString stringWithFormat:@"%@ %@", [userObject objectForKey:@"First"], [userObject objectForKey:@"Last"]] ftime:[object objectForKey:@"Timestamp"] fmsg:[Def decodeFromPercentEscapeString:[object objectForKey:@"Thumbprint"]]]];
[tableView reloadData];

1 个答案:

答案 0 :(得分:1)

您需要将ftime转换为NSDate,因为排序字符串和数字通常会产生不同的结果。因此,假设您已将ftime转换为NSDate,您将使用:

NSSortDescriptor *sd = [NSSortDescriptor sortDescriptorWithKey:@"ftime" ascending:NO];
[listArray sortUsingDescriptors:@[sd]];