63

When I insert new object I do with following code:

NSManagedObjectContext *context = [appDelegate managedObjectContext];

Favorits *favorits = [NSEntityDescription insertNewObjectForEntityForName:@"Favorits" inManagedObjectContext:context];

favorits.title = @"Some title";

NSError *error;                    
if (![context save:&error]) {
    NSLog(@"Whoops");
}

How can I update existing object in core data?

Lorenzo B
  • 33,216
  • 24
  • 116
  • 190
iWizard
  • 6,816
  • 19
  • 67
  • 103

5 Answers5

135

Updating is simple as creating a new one.

To update a specific object you need to set up a NSFetchRequest. This class is equivalent to a SELECT statetement in SQL language.

Here a simple example:

NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Favorits" inManagedObjectContext:moc]];

NSError *error = nil;
NSArray *results = [moc executeFetchRequest:request error:&error];

// error handling code

The array results contains all the managed objects contained within the sqlite file. If you want to grab a specific object (or more objects) you need to use a predicate with that request. For example:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"title == %@", @"Some Title"];
[request setPredicate:predicate]; 

In this case results contains the objects where title is equal to Some Title. Setting a predicate is equal to put the WHERE clause in a SQL statement.

For further info I suggest you to read the Core Data programming guide and NSFecthRequest class reference.

Hope it helps.

EDIT (snippet that can be used to update)

// maybe some check before, to be sure results is not empty
Favorits* favoritsGrabbed = [results objectAtIndex:0];    
favoritsGrabbed.title = @"My Title";

// save here the context

or if you are not using a NSManagedObject subclass.

// maybe some check before, to be sure results is not empty
NSManagedObject* favoritsGrabbed = [results objectAtIndex:0];
[favoritsGrabbed setValue:@"My title" forKey:@"title"];

// save here the context

In both cases if you do a save on the context, data will be updated.

Community
  • 1
  • 1
Lorenzo B
  • 33,216
  • 24
  • 116
  • 190
  • @CroiOS My example is very simple and does not take in consideration memory management. – Lorenzo B May 13 '12 at 13:30
  • thank's. Can you update pls your post and add example code for updateing this object whuch I grabed. I'm here: Favorits *myObject = [array objectAtIndex:0]; .. what's next? – iWizard May 13 '12 at 13:31
  • @CroiOS I added an edit. As I already commented, the code is very simple and you need to do some check before. This is only to guide you on modifying your managed object once retrieved. P.S. Check the code because I've written by hand. Hope it helps. – Lorenzo B May 13 '12 at 13:36
  • @flexaddicted How we can update all objects of an entity suppose having boolean property to value NO? – The iCoder Jun 09 '14 at 07:02
  • 3
    @PavanMore You need to create a request, modify the property you are interested in and do a save – Lorenzo B Jun 09 '14 at 07:54
  • 1
    Thanks for pointing out I don't have to subclass `NSManagedObject` at all to make this work! – ctietze Nov 13 '14 at 14:06
  • @LorenzoBoaro I am using your method in button so what to write on objectAtIndex rather then 0 [results objectAtIndex:0]. – Muju Jan 06 '17 at 07:21
11

You have to fetch the object from the context, change the properties you desire, then save the context as you are in your example.

shawnwall
  • 4,549
  • 1
  • 27
  • 38
  • 1
    @CroiOS You change the properties exactly the same way you set them initially. You also save them exactly the same way. – sosborn May 13 '12 at 13:30
7

I hope this will help u. as it works for me.

 NSMutableArray *results = [[NSMutableArray alloc]init];
int flag=0;
NSPredicate *pred;
if (self.txtCourseNo.text.length > 0) {
    pred =  [NSPredicate predicateWithFormat:@"courseno CONTAINS[cd] %@", self.txtCourseNo.text];
    flag=1;
} else {
    flag=0;
    NSLog(@"Enter Corect Course number");
}

if (flag == 1) {

    NSLog(@"predicate: %@",pred);
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]initWithEntityName:@"Course"];
    [fetchRequest setPredicate:pred];
    results = [[self.context executeFetchRequest:fetchRequest error:nil] mutableCopy];


    if (results.count > 0) {
        NSManagedObject* favoritsGrabbed = [results objectAtIndex:0];
        [favoritsGrabbed setValue:self.txtCourseName.text forKey:@"coursename"];
        [self.context save:nil];
        [self showData];
    } else {
        NSLog(@"Enter Corect Course number");
    }



}
Patel Jigar
  • 2,141
  • 1
  • 23
  • 30
4

if you are a swift programmer this can help you :

if you want to delete a NSManagedObject

in my case ID is a unique attribute for entity STUDENT

/** for deleting items */

func delete(identifier: String) {

    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "STUDENT")
    let predicate = NSPredicate(format: "ID = '\(identifier)'")
    fetchRequest.predicate = predicate
    do
    {
        let object = try context.fetch(fetchRequest)
        if object.count == 1
        {
            let objectDelete = object.first as! NSManagedObject

                 context.delete(objectDelete)
        }
    }
    catch
    {
        print(error)
    }
} 

if you want to update a NSManagedObject :

/** for updating items */
func update(identifier: String,name:String) {

    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "STUDENT")
    let predicate = NSPredicate(format: "ID = '\(identifier)'")
    fetchRequest.predicate = predicate
    do
    {
        let object = try context.fetch(fetchRequest)
        if object.count == 1
        {
            let objectUpdate = object.first as! NSManagedObject
            objectUpdate.setValue(name, forKey: "name")
            do{
                try context.save()
            }
            catch
            {
                print(error)
            }
        }
    }
    catch
    {
        print(error)
    }
}
Mohammad Reza Koohkan
  • 1,656
  • 1
  • 16
  • 36
1

I saw an answer in Objective-C which helped me. I am posting an answer for Swift users -

guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
    return
}
let updateCont = appDelegate?.persistentContainer.viewContext
let pred = NSPredicate(format: "your_Attribute_Name = %@", argumentArray : [your_Arguments])
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "your_Entity_Name")
request.predicate = pred

do {
    let resul = try updateCont?.fetch(request) as? [NSManagedObject]
    let m = resul?.first
    m?.setValue(txtName.text, forKey: "your_Attribute_Name_Whose_Value_Should_Update")
    try? updateCont?.save()
} catch let err as NSError {
    print(err)
}
pkamb
  • 33,281
  • 23
  • 160
  • 191
Ashutosh Shukla
  • 358
  • 5
  • 14