[英]Sorting an NSMutable Array of NSMutable dictionaries
I am an Iphone developer and I am new to this technology. 我是Iphone开发人员,并且是该技术的新手。 I want to sort an NSMutableArray
. 我想对NSMutableArray
进行排序。 At every index of this array, there is an NSMutableDictionary
. 在此数组的每个索引处,都有一个NSMutableDictionary
。 Every dictionary has two fields : Name and Date. 每个词典都有两个字段:名称和日期。 I want to sort the array according to this Date field . 我想根据此Date字段对数组进行排序。 My array looks like following : 我的数组如下所示:
(
{
name : raj
date : 20/09/1998
}
{
name : teena
date : 21/06/1987
}
)
I searched on net a lot but couldn't find any appropriate answer. 我在网上进行了大量搜索,但找不到任何合适的答案。 Please help me guys. 请帮助我。 Any response will highly be appreciated. 任何回应将不胜感激。
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"date"
ascending:YES] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
self.sortedArray = [self.originalArray sortedArrayUsingDescriptors:sortDescriptors];
This should work if your date key actually contains a date object and if it contains a date in the form of string.. than you will have to try this.. 如果您的日期键实际上包含一个日期对象,并且包含一个字符串形式的日期,则此方法应该起作用。
[resultArray sortUsingComparator:^NSComparisonResult(id a, id b) {
static NSDateFormatter *dateFormatter = nil;
if (!dateFormatter) {
dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"mm/dd/yyyy hh:mm:ss";
}
NSString *date1String = [a valueForKey:@"StartDate"];
NSString *date2String = [b valueForKey:@"StartDate"];
NSDate *date1 = [dateFormatter dateFromString:date1String];
NSDate *date2 = [dateFormatter dateFromString:date2String];
return [date1 compare:date2];
}];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.