Tuesday, May 20, 2014

Updating values - Core Data

Procedure

1. Create context object

 AppDelegate *app=[[UIApplication sharedApplication]delegate];

    NSManagedObjectContext *Obj=[app managedObjectContext];

2. Create Fetch request 

 NSFetchRequest * request = [[NSFetchRequest alloc] init];

    [request setEntity:[NSEntityDescription entityForName:@"Stations" inManagedObjectContext:Obj]];

    [request setPredicate:[NSPredicate predicateWithFormat:@"name ==%@",@"Sample string"]];
    
    
3. Execute request  and save the result in managed object (aBook is managed object class)
   
    aBook = [[Obj executeFetchRequest:request error:&error2] lastObject];

4. Check for error

 if (error2) {
        //Handle any errors
    }
    
    if (!aBook) {
        //Nothing there to update
    }
    

5. Update value and saving 

   
    aBook.name = @"BarBar";
    
    //Save it
    error2 = nil;
    if (![Obj save:&error2]) {
        //Handle any error with the saving of the context
    }

No comments:

Post a Comment