【问题标题】:Fetch object by property in Core Data在 Core Data 中按属性获取对象
【发布时间】:2009-09-17 12:33:14
【问题描述】:

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

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

我该怎么做?

【问题讨论】:

    标签: iphone objective-c core-data


    【解决方案1】:

    以下 sn-p 显示如何检索与特定谓词匹配的对象。如果没有这样的对象,sn-p 显示如何创建一个新对象,保存并返回它。

        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;
    
       }
    

    【讨论】:

    • aFetchedResultsController 的意义何在?我是否误以为您创建了它,但从不使用它来做任何事情?
    • 你是对的,在这个特定的例子中,NSFetchedResultsController 没有被使用,但它应该在一个真实的应用程序的上下文中(它简化了许多其他的事情,并提供了一个很好的缓存机制)。跨度>
    【解决方案2】:

    如果您想检查本地数据的某些属性,最好不要进行多次提取。只需使用预先填充的数组执行一次获取请求,然后迭代或过滤结果。

    这是来自核心数据编程指南“高效实现查找或创建”的代码 sn-p:

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

    【讨论】:

      猜你喜欢
      • 2012-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-22
      相关资源
      最近更新 更多