Abhishek Patel
Abhishek Patel

Reputation: 71

update data in xcdatamodel in iphone

i have ios application with xcdatamodeld, i want update some data so need a code for that

i have code for insert

NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
[newManagedObject setValue:txtName.text forKey:@"name"];   [newManagedObject setValue:txtid.text forKey:@"id"];     
// Save the context.
NSError *error = nil;
if (![context save:&error]) {      
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
}

and for delete

NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
    [context deleteObject:[self.fetchedResultsController objectAtIndexPath:indexPath]];

but i need code for update my data.

Upvotes: 0

Views: 175

Answers (2)

Abhishek Patel
Abhishek Patel

Reputation: 71

   NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
    NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];       
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entity];     

    request.predicate = [NSPredicate predicateWithFormat:@"id == %@", strId];        
    NSArray *fetchResults = [self.fetchedResultsController.managedObjectContext executeFetchRequest:request error:nil];       

    [fetchResults setValue:txtName.text forKey:@"name"];
    [fetchResults setValue:txtPhone.text forKey:@"phone"];
    [fetchResults setValue:txtEmail.text forKey:@"email"];

    NSError *error = nil;
    if (![context save:&error]) {        
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

Upvotes: 0

Scott Berrevoets
Scott Berrevoets

Reputation: 16946

You can simply select the data using an NSFetchRequest (and possibly sort descriptors and predicates). You will get back an array with the results of that fetch request. These results are all of the type of entity you selected from, and then all you need to do is update those subclass' properties. An example would be something like this:

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntity:@"Car"];
request.predicate = [NSPredicate predicateWithFormat:@"make == %@", @"Ford"]; // make is an attribute of the Car entity

NSArray *fetchResults = [self.fetchedResultsController.managedObjectContext executeFetchRequest:request error:nil];
Car *car = [fetchResults objectAtIndex:0]; // First result
car.make = @"Chevrolet";

Now your Core Data backend will automatically be updated to have a Car object whose make is Chevrolet.

Upvotes: 1

Related Questions