2012-12-19 55 views
1

我有一个EntityCoreData模仿MySQL数据库表结构如下:SQL语句和单一核心数据获取请求

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组合,NSSortDescriptorNSPredicate,我可以用iOS达到相同的结果吗?

我使用了以下内容:

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?例如,PhotographerPhotos有一对多的关系?

+0

'photographerName' - >'photographer'? – paulmelnikow

回答

1

首先,它肯定是更好和更灵活的设计有关系Photo - Photographer

但是,你想要的也可以实现。你只能得到照片实体,所以你必须过滤结果数组才能返回摄影师的名字。

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

正如您所看到的,这非常麻烦。此外,您已经失去了与每位摄影师相关的照片信息。

所以,请与关系。毕竟,核心数据是一个对象图,而不是数据库封装。

+0

+1并接受最后一句。带两个'NSEntities'。 –