我有一個NSMutableArray的使用詞典,所有字典的中包含的NSDate是關鍵「日期」的NSString的形式。我想按日期排列NSDictionaries。因此,例如,我有數組的狀態如下:排序NSDictionaries通過NSDate的
Dict
Date
20.06.1996 23:30
Dict
Date
04.10.2011 19:00
Dict
Date
20.06.1956 23:39
我想對它進行排序,使它看起來像這樣:
Dict
Date
20.06.1956 23:39
Dict
Date
20.06.1996 23:30
Dict
Date
04.10.2011 19:00
我已經與NSSortDescriptor嘗試,但都沒有成功...
更新:
我設法日期排序,但是我來到了這個問題:在類型的字典,不僅有日期,還有其他對象,什麼我的鱈魚e是否只是切換字典之間的日期值,而不是切換完整的字典。有了這個,字典中的其他值就被分配了錯誤的日期,這非常糟糕。有誰能夠幫助我?下面是我的代碼:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"savedData.daf"];
NSMutableArray *d = [NSMutableArray arrayWithContentsOfFile:path];
for (int ii = 0; ii < [d count]; ii++) {
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
if (is24h) {
[dateFormatter setDateFormat:@"dd.MM.yyyy HH:mm"];
}
else {
[dateFormatter setDateFormat:@"dd.MM.yyyy hh:mm a"];
}
[dateFormatter setLocale:[NSLocale currentLocale]];
NSDate *dat = [dateFormatter dateFromString:[[d valueForKey:@"Date"] objectAtIndex:ii]];
NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
NSDictionary *oldDict = (NSDictionary *)[d objectAtIndex:ii];
[newDict addEntriesFromDictionary:oldDict];
[newDict setObject:dat forKey:@"Date"];
[d replaceObjectAtIndex:ii withObject:newDict];
[newDict release];
}
NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:@"Date" ascending:YES];
NSArray *sorters = [[NSArray alloc] initWithObjects:sorter, nil];
[sorter release];
NSMutableArray *sorted = [NSMutableArray arrayWithArray:[d sortedArrayUsingDescriptors:sorters]];
[sorters release];
NSLog(@"%@",sorted);
for (int ii = 0; ii < [sorted count]; ii++) {
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
if (is24h) {
[dateFormatter setDateFormat:@"dd.MM.yyyy HH:mm"];
}
else {
[dateFormatter setDateFormat:@"dd.MM.yyyy hh:mm a"];
}
[dateFormatter setLocale:[NSLocale currentLocale]];
NSString *sr = [dateFormatter stringFromDate:[[sorted valueForKey:@"Date"] objectAtIndex:ii]];
NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
NSDictionary *oldDict = (NSDictionary *)[d objectAtIndex:ii];
[newDict addEntriesFromDictionary:oldDict];
[newDict setObject:sr forKey:@"Date"];
[sorted replaceObjectAtIndex:ii withObject:newDict];
[newDict release];
}
NSLog(@"before: %@"
""
"after: %@",d,sorted);
[sorted writeToFile:path atomically:YES];
你應該張貼你不能讓工作的代碼。 – vikingosegundo
我很困惑。他們是否包含NSDates或NSStrings?你說兩個,但一個對象不能同時是一個NSDate和一個NSString。 – Chuck
這是NSStrings,對不起! – JonasG