gpt4 book ai didi

iphone - 核心数据 - 不同的结果在 fetchedResultsController 中不起作用

转载 作者:行者123 更新时间:2023-12-03 21:03:57 24 4
gpt4 key购买 nike

我花了几个小时试图弄清楚以下问题......

我的 iPhone 应用程序中有以下核心数据 fetchResultsController,尽管在我的代码中设置了以下内容,但它不会返回一组不同的值...

// Only distinct values
[fetchRequest setReturnsDistinctResults:YES];

以下是整个fetchResultController...

- (NSFetchedResultsController *)fetchedResultsController
{
if (__fetchedResultsController != nil) {
return __fetchedResultsController;
}

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

[fetchRequest setEntity:[NSEntityDescription entityForName:@"CardMessage"inManagedObjectContext:self.managedObjectContext]];

// Set the properties to fetch
NSArray *propertiesToFetch = [[NSArray alloc] initWithObjects:@"category", nil];
[fetchRequest setPropertiesToFetch:propertiesToFetch];

// Only distinct values
[fetchRequest setReturnsDistinctResults:YES];

// Order the output
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"category" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];

[fetchRequest setSortDescriptors:sortDescriptors];

// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc]
initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext
sectionNameKeyPath:nil
cacheName:@"Master"];

aFetchedResultsController.delegate = self;

self.fetchedResultsController = aFetchedResultsController;

NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error]) {
/*
Replace this implementation with code to handle the error appropriately.

abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
*/
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}

return __fetchedResultsController;
}

最佳答案

您的 propertiesToFetch 数组包含一个字符串。它应该包含一个NSPropertyDescription。 (在本例中,它将是其子类,NSAttributeDescription。)

NSArray *propertiesToFetch = [[NSArray alloc] initWithObjects:
[entity.propertiesByName objectForKey:@"category"],
nil];

(现代 Objective-C)

NSArray *propertiesToFetch = @[entity.propertiesByName[@"category"]]; 

如果您仍然得到重复条目,只需使用 NSSet 来获取唯一值。

NSSet *uniqueProperties = [NSSet setWithArray:resultsArray]; 

关于iphone - 核心数据 - 不同的结果在 fetchedResultsController 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9546050/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com