Programmatically Update an attribute in Core Data

前端 未结 5 729
被撕碎了的回忆
被撕碎了的回忆 2020-12-23 15:11

I\'ve looked through all the class documentation for Core Data and I can\'t find away to programmatically update values in a core data entity. For example, I have a structur

5条回答
  •  滥情空心
    2020-12-23 15:37

    In Core Data, an object is an object is an object - the database isn't a thing you throw commands at.

    To update something that is persisted, you recreate it as an object, update it, and save it.

    NSError *error = nil;
    
    //This is your NSManagedObject subclass
    Books * aBook = nil;
    
    //Set up to get the thing you want to update
    NSFetchRequest * request = [[NSFetchRequest alloc] init];
    [request setEntity:[NSEntityDescription entityForName:@"MyLibrary" inManagedObjectContext:context]];
    [request setPredicate:[NSPredicate predicateWithFormat:@"Title=%@",@"Bar"]];
    
    //Ask for it
    aBook = [[context executeFetchRequest:request error:&error] lastObject];
    [request release];
    
    if (error) {
    //Handle any errors
    }
    
    if (!aBook) {
        //Nothing there to update
    }
    
    //Update the object
    aBook.Title = @"BarBar";
    
    //Save it
    error = nil;
    if (![context save:&error]) {
               //Handle any error with the saving of the context
    }
    

提交回复
热议问题