1

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];
2
  • Why didn't the code in that answer work for you? Show the code you tried and what result it gave you. Commented Apr 9, 2014 at 4:30
  • ended up having to do with how I was converting my NSString to NSDate but the answer provided works great for me Commented Apr 9, 2014 at 15:31

1 Answer 1

1

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]];
Sign up to request clarification or add additional context in comments.

1 Comment

simple and clean and works now that I'm converting to NSDate correctly thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.