使用谓词对核心数据进行排序以消除重复

Posted

技术标签:

【中文标题】使用谓词对核心数据进行排序以消除重复【英文标题】:Sorting Core Data with Predicate to eliminate duplicates 【发布时间】:2010-12-19 13:15:01 【问题描述】:

我将一个事件数据库加载到具有重复事件标题的核心数据中。这样做是为了让数据库可以为活动的每一天提供独特的信息。例如,每个日期的价格波动。

我现在需要从列表中删除重复的事件标题,该列表将显示为带有 NSFetchRequest 和 NSPredicate 的表视图以提供过滤器。但是我看到的所有示例都需要将非动态键值用作谓词过滤器的目标。例如,下面的 NSDate 提供了现在作为关键过滤器的时间,并且它可以工作。

目前 NSString * title 以事件 ManagedObject 类中的一个值为目标,该值返回一个 nil 值。这是 FetchResultsController 的一个片段。

- (NSFetchedResultsController *)fetchedResultsController 
    if (fetchedResultsController == nil) 
        NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init] autorelease];
        NSPredicate *predicate = [[[NSPredicate alloc] init] autorelease];
        [fetchRequest setReturnsObjectsAsFaults:NO];  
        [fetchRequest setEntity:[NSEntityDescription entityForName:@"Event" inManagedObjectContext:managedObjectContext]];
        NSArray *sortDescriptors = nil;
        NSString *sectionNameKeyPath = nil;
        NSDate *date = [NSDate date];
        NSString *title = [events title];
        if ([fetchSectioningControl selectedSegmentIndex] == 1) 
            predicate = [NSPredicate predicateWithFormat:@"(closeDate >= %@) AND (title == %@)", date, title ];
            sortDescriptors = [NSArray arrayWithObjects:[[[NSSortDescriptor alloc] initWithKey:@"category.name" ascending:YES] autorelease], [[[NSSortDescriptor alloc] initWithKey:@"openDate" ascending:YES] autorelease], nil];
            sectionNameKeyPath = @"category.name";
         else if ([fetchSectioningControl selectedSegmentIndex] == 0)
            predicate = [NSPredicate predicateWithFormat:@"closeDate >= %@", date];
            sortDescriptors = [NSArray arrayWithObject:[[[NSSortDescriptor alloc] initWithKey:@"openDate" ascending:YES selector:@selector(compare:)] autorelease]];
            sectionNameKeyPath = @"day"; 
        
        [fetchRequest setPredicate:predicate];
        [fetchRequest setSortDescriptors:sortDescriptors];
        fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:sectionNameKeyPath cacheName:@"EventsCache"];
        
    return fetchedResultsController;

【问题讨论】:

【参考方案1】:

你可以设置

setReturnsDistinctResults:YES

在您的 fetchRequest 上。

有关更多信息,请参阅文档: NSFetchRequest Class Reference

【讨论】:

感谢您的反馈。不幸的是,在这个阶段它提供的问题多于解决方案。据我所知,结果需要作为 NSDictionary 返回,因此我失去了它们作为托管对象返回的一些功能。 IE。数据还与我之前没有提到的另一个名为“类别”的实体有关系,appologies。它定义了每个事件的部分。

以上是关于使用谓词对核心数据进行排序以消除重复的主要内容,如果未能解决你的问题,请参考以下文章

按 ID 对核心数据进行排序 [重复]

在SELECT语句中,对查询结果进行排序的子句是啥?能消除重复行的关键字是啥?

删除重复项:如何为 boost::geometry::box 编写排序谓词?

论文泛读168对训练数据进行重复数据消除会使语言模型变得更好

论文泛读168对训练数据进行重复数据消除会使语言模型变得更好

如何以正确的顺序对月份进行排序 Jan-Dec Pandas [重复]