2009-09-17 123 views
10

在我的iPhone項目中,我想編寫一個函數,檢查Core Data ManagedObjectContext中是否存在某個特定值的對象,如some_property通過核心數據中的屬性獲取對象

如果已經有一個對象some_property == 12,我想讓該函數返回該對象,否則,我想創建該對象,或者至少返回nil

我該怎麼做?

回答

19

以下片段顯示如何檢索匹配特定謂詞的對象。如果沒有這樣的對象,代碼片段展示瞭如何創建一個新的對象,保存並返回它。

NSFetchRequest *request = [[NSFetchRequest alloc] init]; 
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"YourEntityName" inManagedObjectContext:managedObjectContext]; 
    [request setEntity:entity]; 
    // retrive the objects with a given value for a certain property 
    NSPredicate *predicate = [NSPredicate predicateWithFormat: @"property == %@", value]; 
    [request setPredicate:predicate]; 

    // Edit the sort key as appropriate. 
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"yourSortKey" ascending:YES]; 
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; 
    [request 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:request managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:@"Root"]; 
    aFetchedResultsController.delegate = self; 

    NSError *error = nil; 
    NSArray *result = [managedObjectContext executeFetchRequest:request error:&error]; 

    [request release]; 
    [sortDescriptor release]; 
    [sortDescriptors release]; 


    if ((result != nil) && ([result count]) && (error == nil)){ 
     return [NSMutableArray arrayWithArray:result]; 
    } 
    else{ 
     YourEntityName *object = (YourEntityName *) [NSEntityDescription insertNewObjectForEntityForName:@"YourEntityName" inManagedObjectContext:self.managedObjectContext]; 
      // setup your object attributes, for instance set its name 
      object.name = @"name" 

      // save object 
      NSError *error; 
      if (![[self managedObjectContext] save:&error]) { 
      // Handle error 
      NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 

      } 

      return object; 

    } 
+0

哇,那是快!讓我試試這個...... – winsmith 2009-09-17 13:21:26

+0

'aFetchedResultsController'有什麼意義?我錯誤地認爲你創造它,但從來沒有用它做任何事情? – ArtOfWarfare 2013-06-30 04:30:58

+0

你是對的,在這個特殊的例子中,NSFetchedResultsController沒有被使用,但它應該在真實應用程序的上下文中(它簡化了許多其他的事情,並提供了一個很好的緩存機制)。 – 2013-06-30 08:32:51

2

如果您想檢查本地數據的某些屬性,最好不要多次抓取。只需使用預先填充的數組執行一個獲取請求,然後迭代或過濾結果。

這是從核心數據編程指南代碼段「實現查找 - 或 - 創建高效」:

// get the names to parse in sorted order 
NSArray *employeeIDs = [[listOfIDsAsString componentsSeparatedByString:@"\n"] 
     sortedArrayUsingSelector: @selector(compare:)]; 

// create the fetch request to get all Employees matching the IDs 
NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init] autorelease]; 
[fetchRequest setEntity: 
     [NSEntityDescription entityForName:@"Employee" inManagedObjectContext:aMOC]]; 
[fetchRequest setPredicate: [NSPredicate predicateWithFormat: @"(employeeID IN %@)", employeeIDs]]; 

// make sure the results are sorted as well 
[fetchRequest setSortDescriptors: [NSArray arrayWithObject: 
     [[[NSSortDescriptor alloc] initWithKey: @"employeeID" 
       ascending:YES] autorelease]]]; 
// Execute the fetch 
NSError *error; 
NSArray *employeesMatchingNames = [aMOC 
     executeFetchRequest:fetchRequest error:&error];