2012-03-03 51 views
2

工作,我已經花時間試圖找出下列出...核心數據 - 獨特的成果不是在fetchedResultsController

我在我的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; 
}  

回答

2

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]; 
+0

感謝您的快速響應,但它仍然返回實體中的所有行 – rs2000 2012-03-03 13:32:37

+0

您可以使用NSSet。往上看。 – Mundi 2012-03-03 16:49:16

+0

乾杯不得不使用NSSet ...有點困惑爲什麼[fetchRequest setReturnsDistinctResults:YES];沒有工作... PS ...它似乎工作作爲一般的獲取請求... – rs2000 2012-03-04 13:03:03

0

注無論是從setPropertiesToFetch文檔的言論:

  1. 你必須爲這個設定值之前的讀取請求的實體,否則NSFetchRequest拋出NSInvalidArgumentException例外。

  2. 此值僅在resultType設置爲NSDictionaryResultType時使用。

請注意,resultType的默認值是NSManagedObjectResultType。