I am playing around with a new project, a split view iPad app using Core Data, and I was wondering, as its fairly clear how to add and remove an item. If I
http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CoreData/Articles/cdFetching.html will show you how to fetch an entity,
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreData/Articles/cdUsingMOs.html will show you how to change properties, and save them.
core data is something where you really want to read a lot of the apple documentation and become familiar, it will save you hours in the long run. hope this helps!
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.