Alessandro
Alessandro

Reputation: 4100

Order an NSMutableArray with dates

I have an NSMutableArray of file names, and I can access these files modification date:

NSMutableDictionary* dict = [[NSMutableDictionary alloc]init];
for (NSString* str in documentsArray) {
    NSString* str2 = [DKStoreManager dateFileWasModifiedWithFileName:str inFolderNumber:folderNumber forUser:userID andType:type];
    [dict setObject:str2 forKey:str];
}
NSArray * dateArray = [dict allValues];
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"self" ascending:NO];
NSArray *descriptors = [NSArray arrayWithObject: descriptor];

NSArray *reverseOrder = [dateArray sortedArrayUsingDescriptors:descriptors];

NSMutableArray* arr2 = [[NSMutableArray alloc]init];
for (NSString * date in reverseOrder){
    NSArray *temp = [dict allKeysForObject:date];

    NSString * your_value = [dict valueForKey:[temp lastObject]];
    [arr2 addObject:your_value];
}
return arr2;

documentsArray is simply a list of file names, like this:

"ale and  1.png",
"yyyy 1.png",
"the fact that  1.png",

I am trying to put together the name with the correspondent date in a dictionary, and then order the dictionary dates, which I set us objects, and finally get back the ode red list of file names. If I use the file names as object and the dates as key, some dates are equal, so they will only be accepted once. If on the other hand I use as objects the dates, then I can't get back to the keys...

Upvotes: 0

Views: 69

Answers (1)

lucianomarisi
lucianomarisi

Reputation: 1552

I would suggest you create your own model object and use that instead of using NSDictionary. For example:

@interface Model : NSObject

@property (nonatomic, strong) NSDate *someDate;
@property (nonatomic, copy) NSString *someString;


- (instancetype)initWithString:(NSString *)string date:(NSDate *)date;

@end

@implementation Model


- (instancetype)initWithString:(NSString *)string date:(NSDate *)date
{
    self = [super init];
    if (self) {
        _someString = [string copy];
        _someDate = date;
    }
    return self;
}

@end

Then if you have an NSArray of these Models you could use KVC to get an array of the particular key and do whatever you need, for example:

Model *model1 = [[Model alloc] initWithString:@"Model 1"
                                         date:[NSDate dateWithTimeIntervalSinceNow:10]];
Model *model2 = [[Model alloc] initWithString:@"Model 2"
                                         date:[NSDate dateWithTimeIntervalSinceNow:20]];
NSArray *array = @[model1, model2];

NSLog(@"stringArray:%@", [array valueForKey:@"someString"]);
NSLog(@"dateArray:%@", [array valueForKey:@"someDate"]);

Upvotes: 1

Related Questions