Reputation: 3852
I have a UIViewController
, which has Save button in UINavigationBar
.
This UIViewController
is used for saving a New User as well as Editing a User.
On, save button I used to always call - (void)insertObject:(NSManagedObject *)object;
which fails when I am editing a user, as that managed object is already available.
So, I am using the following check. Is this is the correct way for insert or saving editing user?
NSManagedObject *managedObject = someObject;
NSManagedObjectContext *managedContext = someContextObject;
NSError *error;
if(m.objectID.isTemporaryID){
//This means its a new object so, first insert
[managedContext insertObject:managedObject];
}
[managedContext save:&error];
Upvotes: 0
Views: 125
Reputation: 18487
My pattern for this is to create a property on the view controller for my managed object. Pretending that your user class is User
:
@property (nonatomic, strong) User *user;
If I am doing an edit the property will be set with an existing user. If I am doing a create it will be nil
. In my save logic I do a check:
- (void)didSelectSaveButton:(id)sender {
if (!self.user) {
self.user = [NSEntityDescription insertNewObjectForEntityForName:@"User"
inManagedObjectContext:context];
}
// Rest of the logic to map the UI elements to the properties of my user model
// objects, referencing self.user
NSError *error = nil;
BOOL success = [managedObjectContext save:&error];
// error handling
}
This way, my logic for populating the information for a user is the same, regardless if it is an "insert" or "update".
Upvotes: 1