2012-12-19 58 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'。 –