簡體   English   中英

如何參考保存在iPhone中作為“鍵對象”的日期對可變數組進行排序?

[英]How to sort a mutable array with reference to Date which is saved as “object for key” in iphone?

我是iPhone開發的新手。我最近有一個可變數組,其中的標題,日期,URL和摘要等值都存儲為“鍵對象”。這些鍵是myurl,mutate,mytitle,mysummary。我想對它進行排序可變數組引用日期,並根據該日期打印所有值。如何實現?請幫幫我。謝謝。

            [item setObject:currentTitle forKey:@"title"];
            [item setObject:currentLink forKey:@"link"];
            [item setObject:currentSummary forKey:@"description"];
            [item setObject:currentDate forKey:@"pubDate"];//
            [item setObject:currentImage forKey:@"imagePath"];

            [recent addObject:[item copy]];

都是xml解析的內容。

因此,我猜您有很多字典。 有兩種方法可以做到這一點,但是我建議使用NSSortDescriptor 您將需要執行以下操作:

//myArray is the name of the your array
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"mydate" ascending:YES]; // If you want newest at the top, pass NO instead.
[myArray sortUsingDescriptor:descriptor]; // This will modify myArray. To return a new array and leave the original untouched, use -sortedArrayUsingDescriptor:.
[descriptor release];
NSLog(@"%@", myArray); // Print.

如果您已經將日期作為NSDate對象,則可以正常使用。 如果不是,則需要循環遍歷數組並事先解析日期,或者使用NSSortDescriptorinitWithKey:ascending:selector:方法,該方法可以定義自定義比較方法。

斯威夫特3.0

 let descriptor = NSSortDescriptor(key: "Your array KEY", ascending: false)

 yourArray.sort(using: [descriptor])

對於升序排序,請將其設為“ true”,否則將其設為“ false”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM