Fetch object by property in Core Data

前端 未结 2 828
故里飘歌
故里飘歌 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:31

    The following snippet shows how to retrieve the objects matching a specific predicate. If there are no such objects, the snippet shows how to create a new object, save it and return it.

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

提交回复
热议问题