如何根据在iphone中保存为"key for object"的Date对可变数组进行排序?

War*_*ior 0 sorting iphone cocoa cocoa-touch nsmutablearray

我是iphone开发的新手.我最近有一个可变数组,其中诸如标题,日期,网址和摘要等值被存储为"密钥对象".密钥是myurl,mudate,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]];
Run Code Online (Sandbox Code Playgroud)

所有都是xml解析的内容.

Col*_*ett 7

所以我猜你有一系列字典.有几种方法可以做到这一点,但我建议使用的方法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.
Run Code Online (Sandbox Code Playgroud)

如果您已将日期作为NSDate对象,则可以正常工作.如果没有,您将需要循环遍历数组并预先解析日期,或使用initWithKey:ascending:selector:方法NSSortDescriptor,这允许您定义自定义比较方法.