Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

   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();
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top