I have core data configuration in my iPhone app, and how I’m currently passing the configuration to the view that allows a user to EDIT the data, is via passing the core data object by reference. In fact I’m allocated the core data class attribute (NSString) to the “UITextField.text” in the edit view, so that if it gets updated then it is effectively updating the core data object. The issue is:
- it seems to work fine when I create/update this string in the edit view
- when I update a separate field (not the one in question) then the value seems to be null
Question – Is there anything fundamentally wrong with this pass-by-reference approach using a core-data managed object attribute?
Code snippets:
a) In the Edit Controller – in cellForRowAtIndexPath
if (indexPath.row == 0) {
// Setup
UITextField *titleTextField = nil;
// Get Cell
self.nonWorkTermCell = [tableView dequeueReusableCellWithIdentifier:@"nonWorkTermCell"];
if (self.nonWorkTermCell == nil) {
self.nonWorkTermCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"nonWorkTermCell"] autorelease];
self.nonWorkTermCell.textLabel.text = @"Non Work Term:";
titleTextField = [[self newTextFieldForCell:self.nonWorkTermCell] autorelease];
titleTextField.keyboardType = UIKeyboardTypeURL;
titleTextField.returnKeyType = UIReturnKeyDone;
titleTextField.delegate = self; // TODO: Is this needed at all?
titleTextField.tag = 1;
[self.nonWorkTermCell addSubview:titleTextField];
}
// Set Value
titleTextField.text = self.weConfig.nonWorkTerm; // ** ASSIGNS THE CORE DATA MANAGED OBJECT CONFIG ITEM DIRECTLY TO THE TEXT FIELD
// Return
return self.nonWorkTermCell;
b) and the helper method it uses:
- (UITextField *)newTextFieldForCell:(UITableViewCell *)cell {
UITextField *addTextField = [[UITextField alloc] initWithFrame:frame]; //cut the code for the frame to save space
addTextField.autocorrectionType = UITextAutocorrectionTypeNo;
addTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
addTextField.delegate = self;
addTextField.clearButtonMode = UITextFieldViewModeNever;
addTextField.enabled = YES;
addTextField.returnKeyType = UIReturnKeyDone;
addTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return addTextField;
}
c) then back in the delegate
- (void)applicationWillResignActive:(UIApplication *)application {
[self saveContext];
}
- (void)applicationWillTerminate:(UIApplication *)application {
[self saveContext];
}
Assigning a managed object’s NSString property to a textField and the editing the textfield’s content will not propagate those changes back to the managed object, for a number of reasons: