2012-05-20 125 views
4

(准备目睹一位新手对我所假设的逻辑非常非常困惑,这是我的大脑难以掌握的基本逻辑形式。)如何根据属性列表中的日期对我的UITableViewCells进行排序?

我现在有一个.plist文件。在“Key”列中有事件名称(目前只是虚拟内容),在“Value”列中有以下格式的日期:19-07-2012。每行都是“字符串”类型。

在viewDidLoad方法,我用下面的代码:

NSString *theFile = [[NSBundle mainBundle] pathForResource:@"dates" ofType:@"plist"]; 
theDates = [[NSDictionary alloc] initWithContentsOfFile:theFile]; 
theDatesList = [theDates allKeys]; 

这将加载plist文件到字典,然后我的钥匙加载到一个数组,这是我已经学会了填充方式一个UITableView,特别是与此代码在cellForRowAtIndexPath方法:

NSString *eventFromFile = [theDatesList objectAtIndex:indexPath.row]; 
NSString *dateFromFile = [theDates objectForKey:[theDatesList objectAtIndex:indexPath.row]]; 

但我感到困惑现在的问题是,我该如何订购UITableView的基础上,细胞是什么日期是最快?因此,7月19日的单元格将出现在8月21日之前,无论它在plist文件中的顺序如何。

UITableViewCell之内,我设法计算了当前日期和plist中定义的日期之间的天数。这是该代码:

// Set the date format 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"dd-MM-yyyy"]; 

// Get the current, then future date 
NSDate *currentDate = [NSDate date]; 
NSDate *futureDate = [dateFormatter dateFromString:dateFromFile]; 

// Create the calendar object 
NSCalendar *theCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 

// Extract the "day" component from the calendar object 
NSDateComponents *theDifferenceBetweenDays = [theCalendar components:NSDayCalendarUnit 
                  fromDate:currentDate 
                  toDate:futureDate 
                  options:0]; 

NSInteger theRemainingDays = [theDifferenceBetweenDays day]; 

但我真的不知道我在做什么。有人能给我一个正确的方向吗?我研究了NSSortDescriptorssortedArrayUsingSelector方法,这似乎是相关的,但实际执行的行为让我在过去的六个小时内停滞不前。或者他们可能不是正确的道路。就像我说的,我很困惑。

谢谢。

+0

解决的办法是你的plist中提取到字典的数组,然后对数组进行排序。我不是在Mac ATM机上,所以不必写一个代码示例 - 如果我回来时没有人填空,我会给出一个完整的答案。 – jrturton

+0

实际上,请参阅:http:/ /stackoverflow.com/questions/4824573/how-sorting-array-which-contains-dictionary – jrturton

+0

感谢您的快速描述。不过,该代码示例将非常棒。这只是我尝试过的第二个iOS应用程序(第一个应用程序非常简单得多),所以我很迷茫。 :) – user1191304

回答

-2

monotouch.dialog存在一个客观的C等价性。 与此,它应该很容易。

+1

这与这个问题有什么关系? – jrturton

1

有几种方法可以按降序排序NSArrayNSDates

你可以使用sortedArrayUsingDescriptors:

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"self" ascending:NO]; 
theDatesList = [theDatesList sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]]; 

但我个人更喜欢sortedArrayUsingComparator:

theDatesList = [theDatesList sortedArrayUsingComparator:^NSComparisonResult(NSDate *date1, NSDate *date2){ 
    return [date2 compare:date1]; 
}]; 
相关问题