You simply request the existing object using an NSFetchRequest
, change whatever fields need to be updated (a simple myObject.propertyName setter is all that's required), and then perform a save action on the data context.
EDIT to add code example. I agree with MCannon, Core Data is definitely worth reading up about.
This code assumes you created the project with a template that includes Core Data stuff, such that your app delegate has a managed object context, etc. Note that there is NO error checking here, this is just basic code.
Fetching the object
// Retrieve the context
if (managedObjectContext == nil) {
managedObjectContext = [(YourAppNameAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
}
// Retrieve the entity from the local store -- much like a table in a database
NSEntityDescription *entity = [NSEntityDescription entityForName:@"YourEntityName" inManagedObjectContext:managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entity];
// Set the predicate -- much like a WHERE statement in a SQL database
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"YourIdentifyingObjectProperty == %@", yourIdentifyingQualifier];
[request setPredicate:predicate];
// Set the sorting -- mandatory, even if you're fetching a single record/object
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"yourIdentifyingQualifier" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
[sortDescriptors release]; sortDescriptors = nil;
[sortDescriptor release]; sortDescriptor = nil;
// Request the data -- NOTE, this assumes only one match, that
// yourIdentifyingQualifier is unique. It just grabs the first object in the array.
YourEntityName *thisYourEntityName = [[managedObjectContext executeFetchRequest:request error:&error] objectAtIndex:0];
[request release]; request = nil;
Update the object
thisYourEntityName.ExampleNSStringAttributeName = @"The new value";
thisYourEntityName.ExampleNSDateAttributeName = [NSDate date];
Save the change
NSError *error;
[self.managedObjectContext save:&error];
Now your object/row is updated.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…