1

我有一个模仿具有以下结构的数据库表EntityCoreDataMySQL

Photo
    abv            Double
    photoId        Integer16
    photographer   String
    isActive       Boolean
    lastUpdated    Data
    name           String

我可以运行以下SQL语句来获得我想要的结果集:

SELECT  `photographerName`, COUNT(`photographerName`) 
FROM  `Photos` 
WHERE  `isActive` LIKE 1
GROUP BY  `photographerName` 
ORDER BY  `photographerName` 

我可以使用什么组合NSFetchRequest来获得相同的NSSortDescriptor结果?NSPredicateNSExpressionDescriptioniOS

我正在使用以下内容:

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Photo"];
NSSortDescriptor *photographerSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"photographer" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)];
NSPredicate *onlyActivePhotos = [NSPredicate predicateWithFormat:@"isActive == 1"];

request.sortDescriptors = @[photographerSortDescriptor];
request.predicate = onlyActivePhotos;

self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil];

这让我得到isActive罚款,但为每个返回一行Photo,而不是Photographer.

或者......我应该把它分成两部分Entities吗?例如,与?Photographer具有一对多关系。Photos

4

1 回答 1

1

首先,有关系当然是更好更灵活的设计Photo—— Photographer.

但是,您想要的也可以实现。您只能获取照片实体,因此您必须过滤结果数组以仅返回您的摄影师姓名。

NSArray *photographerNames = [fetchedResultsController.fetchedObjects
   valueForKeyPath:"@photographer"];
NSSet *uniqueNames = [NSSet setWithArray:photographerNames];
NSArray *orderedNames = [uniqueNames sortedArrayUsingDescriptors:
   @[[NSSortDescriptor sortDescriptorWithKey:@"self" ascending:YES]]]; 

如您所见,这非常麻烦。此外,您丢失了与每个摄影师关联的照片的信息。

所以请顺着关系走。毕竟,Core Data 是一个对象图,而不是数据库包装器。

于 2012-12-20T10:11:08.843 回答