2009-09-17 8 views
10

私のiPhoneプロジェクトでは、Core Data ManagedObjectContextに特定のプロパティの値があるオブジェクト、たとえばsome_propertyがあるかどうかをチェックする関数を記述します。Core Dataのプロパティでオブジェクトを取得する

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

+0

'aFetchedResultsController'のポイントは何ですか?私はあなたがそれを作成したと思うのは間違いですが、それを使って何もしませんか? – ArtOfWarfare

+0

この例では、NSFetchedResultsControllerは使用されていませんが、実際のアプリケーションのコンテキスト内にある必要があります(他の多くのものを単純化し、素晴らしいキャッシュメカニズムを提供します)。 –

2

ローカルデータの特定のプロパティをチェックする場合は、複数のフェッチを実行しない方がよい場合があります。あらかじめ設定された配列を使用して1つのフェッチ要求を行い、結果を反復またはフィルタリングするだけです。

これは、コアデータプログラミングガイドからのコードスニペット「の実装を検索・オア・作成効率的」である:

// 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]; 
関連する問題