在Core Data中按属性获取对象

时间:2009-09-17 12:33:14

标签: iphone objective-c core-data

在我的iPhone项目中,我想编写一个函数来检查我的Core Data ManagedObjectContext中是否有一个对象,该对象具有某个属性的给定值,比如some_property

如果已经存在some_property == 12的对象,我希望该函数返回该对象,否则,我想创建该对象,或者至少返回nil

我该怎么做?

2 个答案:

答案 0 :(得分: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;

   }

答案 1 :(得分: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];