Essentially, I have a UITableView with cells that have a UITextField that corresponds with properties (let's say 10+ properties) within a RLMObject. I only allow the user to edit the fields during Edit Mode (via. disabling user interaction). If the user presses Done, I would like for the RLMObject to be committed to the database.
I've added actions to be triggered when the Editing Did end on the textField. The action should update the model of the RLMObject.
I try the following where self.currentProfile is my view's RLMObject property:
- (BOOL) profileTextFieldDidChange:(UITextField *)textField
{
self.currentProfile.name = textField.text; //crashes here
return YES;
}
My Realm Object's class follows (I've taken some of the properties out for simplicity):
@interface Profile : RLMObject
@property (nonatomic) NSString * profileId; // primary key
@property (nonatomic) NSString * name;
@property (nonatomic) NSString * color;
-(id) initWithPrimaryKey;
@end
I get the following error message from the above code: Terminating app due to uncaught exception 'RLMException', reason: 'Attempting to modify object outside of a write transaction - call beginWriteTransaction on an RLMRealm instance first.'
Previous solutions state I should add callBeginWriteTransaction before the change and either commit or cancel depending if the user backs out and cancels the edits or presses done and submits the new profile to the database.
I don't want to add these in my UITableViewController class because I've decoupled my program to have an intermediary data access layer. In the code below, I would like to just throw all the database transactions in my DataAccessServices layer. Is there an alternative solution? I am not Realm expert and am quite new. I would like to note I need to navigate to another view within this view and have additional realm transactions in the other view. If I'm still editing while I segue to the new view--that is I would have nested beginWriteTransactions, would this cause issues?
Thanks in advance.
The current solution that I have that I am not happy with follows:
- (void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
if([self.tableView isEditing]){
RLMRealm *realm = [RLMRealm defaultRealm];
[realm cancelWriteTransaction];
}
NSLog(@"gone...");
}
//Edit Mode --------------------------------
- (IBAction)enterEditMode:(id)sender {
if ([self.tableView isEditing]) { //Turn off Edit Mode
[self.tableView setEditing:NO animated:YES];
[self.editButtonItem setTitle:@"Edit"];
[DataAccessServices saveProfile:self.currentProfile];
[self reloadSections];
RLMRealm *realm = [RLMRealm defaultRealm];
[realm commitWriteTransaction];
}
else {// Turn on edit mode
[self.editButtonItem setTitle:@"Done"];
[self.tableView setEditing:YES animated:YES];
[self reloadSections];
RLMRealm *realm = [RLMRealm defaultRealm];
[realm beginWriteTransaction];
}
}