我的 iPhone 应用程序中有核心数据配置,目前我如何将配置传递到允许用户编辑数据的 View ,是通过引用传递核心数据对象。事实上,我将核心数据类属性(NSString)分配给编辑 View 中的“UITextField.text”,这样,如果它被更新,那么它就会有效地更新核心数据对象。问题是:
- 当我在编辑 View 中创建/更新此字符串时,它似乎工作正常
- 当我更新一个单独的字段(不是有问题的字段)时,该值似乎为空
问题 - 这种使用核心数据托管对象属性的按引用传递方法是否存在根本性错误?
代码片段:
a) 在编辑 Controller 中 - 在 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) 及其使用的辅助方法:
- (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) 然后回到委托(delegate)中
- (void)applicationWillResignActive:(UIApplication *)application {
[self saveContext];
}
- (void)applicationWillTerminate:(UIApplication *)application {
[self saveContext];
}
最佳答案
将托管对象的 NSString 属性分配给文本字段并编辑文本字段的内容将不会将这些更改传播回托管对象,原因如下:
- NSString 是不可变的,因此根据定义,您不会对同一个对象进行更改
- 托管对象上的访问器返回的对象很可能是基础值的自动释放副本
- 文本字段还可能获取分配给其文本属性的任何值的副本
- 除非已通过包含 KVO 通知的托管对象访问器,否则任何更改都不会返回到模型
- 整个想法太疯狂了。如果我想获取从托管对象获取的字符串并对其执行一些其他操作以进行演示或分析,该怎么办?
关于iphone - 这个 UITableView 代码有什么问题,我使用引用传递来更新核心数据配置记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7669047/