2012-05-20 124 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]; 
}]; 
相關問題