Fetch object by property in Core Data

前端 未结 2 838
故里飘歌
故里飘歌 2021-02-08 09:56

In my iPhone project, I want to write a function that checks wether there\'s an object in my Core Data ManagedObjectContext with a given value for a certain property, say

2条回答
  •  北恋
    北恋 (楼主)
    2021-02-08 10:41

    It's better if you don't do multiple fetching if you want to check for certain properties on the local data. Just do one fetch request using a pre-populated array and then iterate or filter the results.

    This is a code snippet from Core Data Programming Guide "Implementing Find-or-Create Efficiently":

    // 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];
    

提交回复
热议问题