Question

I have an array which is used to populate my apps feed which I want to sort by date. I have already looked at this question (https://stackoverflow.com/a/805589/577732) but was unable to get it to work for my array. My classes are below on how I'm creating my object array, any help on sorting my array would be greatly appreciated.

ftime is what I want to sort by it's a timestamp that comes from a mysql database on my server I'm currently storing it with an NSString but can convert to NSDate if needed for sorting.

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];
Was it helpful?

Solution

You will need to convert ftime to NSDate because sorting strings and numbers generally yields different results. Therefore, assuming you have converted ftime to NSDate, you would use:

NSSortDescriptor *sd = [NSSortDescriptor sortDescriptorWithKey:@"ftime" ascending:NO];
[listArray sortUsingDescriptors:@[sd]];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top