【问题标题】:How to sort Dates in objective C?如何在目标 C 中对日期进行排序?
【发布时间】:2016-07-21 06:37:26
【问题描述】:

在我的应用程序中,我在不同日期为单词添加书签,我有排序选项,例如先排序最近的,然后先排序最旧的。我无法根据书签日期对单词进行排序,怎么办?通过使用描述符,我的排序并不好,因为只有前两个条目被排序。我的代码是:

NSSortDescriptor *sortDescriptor1 = [[NSSortDescriptor alloc] initWithKey:@"cellType" ascending:NO selector:@selector(localizedCaseInsensitiveCompare:)];
NSSortDescriptor *sortDescriptor2 = [[NSSortDescriptor alloc] initWithKey:@"entrydate" ascending:NO selector:@selector(localizedCaseInsensitiveCompare:)];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor1, sortDescriptor2, nil];

[self.favoriteEntries sortUsingDescriptors:sortDescriptors];

[[NSUserDefaults standardUserDefaults] setValue:@"descendingDate" forKey:@"BookmarkSortType"];

【问题讨论】:

  • 而不是localizedCaseInsensitiveCompare 尝试@selector(compare:)
  • entrydateNSString 还是 NSDate
  • 这取决于您的数据。 localizedCaseInsensitiveCompare 仅适用于 NSString。如果您的应用在使用该应用时没有崩溃,则说明您的日期是字符串,如果不知道您使用什么格式,我们将无法提供帮助。
  • @Avi 我们使用它作为字符串如何克服它
  • 您应该向我们展示这些日期的字符串表示形式。您可能希望使用NSDateFormatter,然后根据生成的NSDate 对象进行排序,但具体情况会因字符串格式而异。

标签: ios objective-c sorting date nssortdescriptor


【解决方案1】:

您可以使用冒泡排序。它会给您准确的结果而不会造成任何混淆。是的,代码行超过了预定义的功能,但使用冒泡排序是正确的。

【讨论】:

  • 与内置排序类相比,这有什么优势?
  • 进一步解释。你的回答太模糊了。为什么它比其他排序选项更好?
【解决方案2】:

试试这样:

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM/dd/yyyy HH:mm:ss a"];//SET_YOUR_DATE_FORMAT
          NSString *updatedDateStr1 = YOUR_FIRST_DATE_STRING;
          NSDate *date1 = [dateFormatter dateFromString:updatedDateStr1];
          NSString *updatedDateStr2 = YOUR_SECOND_DATE_STRING;
          NSDate *date2 = [dateFormatter dateFromString:updatedDateStr2];
     NSComparisonResult result = [date2 compare:date1];//THIS WILL RETURN ONE OF NSOrderedAscending , NSOrderedSame, NSOrderedDescending

【讨论】:

  • 否,使用正确的数据类型存储数据,在本例中为 NSDate。不断地将NSString 转换为NSDate 以进行比较是非常低效的。
【解决方案3】:

看起来你有NSString 对象。您需要将其转换为 NSDate 对象,然后使用 Predicate 进行比较并根据需要进行排序。修改obj 字典或数组中的任何内容。

NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setDateFormat:@"yyyy-MM-dd"];// Whatever your current stringDate format.
[df setTimeZone:[NSTimeZone systemTimeZone]];
NSPredicate *findFutureDates = [NSPredicate predicateWithBlock: ^BOOL(id obj, NSDictionary *bind){
    NSDate *dd = [df dateFromString:(NSString *)obj ];
    return ([[NSDate date] compare:dd] == NSOrderedAscending);
}];

NSArray *arrFutureDates = [yourArray filteredArrayUsingPredicate: findFutureDates];
NSLog(@"%@",arrFutureDates);

也许这会对你有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多