ios - 已编辑的 UITableViewCell 正在存储为新单元格

标签 ios objective-c core-data

我有一个 TableView ,它的数据源与 Core Data 同步。但是,我遇到了问题。每当我编辑或删除 tableview 单元格并重新加载 View 时,我都会看到 tableview 单元格在编辑之前的副本。这里有一些代码可以使它更清楚。

当 View 首次加载时,它会尝试从具有一对多 关系的“SOModule”中获取所有“SOCommand”。然后,它将其转换为“SOCommandTemp”,这样我就可以在不更改数据库的情况下使用它们。

_serverModuleCommands = [[NSMutableArray alloc]initWithArray:[self.serverModule.socommand allObjects]];
          for(int i=0;i<[_serverModuleCommands count];i++)
          {
               SOCommandTemp* newTemp = [[SOCommandTemp alloc]init];
               newTemp.commandName = ((SOCommand*)[_serverModuleCommands objectAtIndex:i]).commandName;
               newTemp.sshCommand =  ((SOCommand*)[_serverModuleCommands objectAtIndex:i]).sshCommand;
               [_serverModuleCommands replaceObjectAtIndex:i withObject:newTemp];
          }

然后,当我编辑单元格时,我会调用如下方法:

[_serverModuleCommands addObject:commandValues]; //commandValues is in the form of SOCommandTemp

[_serverModuleCommands replaceObjectAtIndex:_selectedCommandCell.row withObject:commandValues]; //_selectedCommandCell is an ivar that is cleared immediately after use

然后,在保存时,我通过这样做将数组转换为 SOCommand:

for(int j=0; j<[_serverModuleCommands count]; j++){

                SOCommand* newCommand = [NSEntityDescription insertNewObjectForEntityForName:@"SOCommand" inManagedObjectContext:self.managedObjectContext];
                newCommand.commandName = ((SOCommandTemp*)[_serverModuleCommands objectAtIndex:j]).commandName;
                newCommand.sshCommand =  ((SOCommandTemp*)[_serverModuleCommands objectAtIndex:j]).sshCommand;
                newCommand.somodule = newModule;                  
}

但是,在调用它之前,我想确保只保存一个数组项,因为我添加并编辑了一个单元格,所以我这样做:

 NSLog(@"Going to Save: %@",[_serverModuleCommands description]);

果然,我只得到 1 个数组项。然后,我保存它,并退出 View Controller 。但是当第一行:

_serverModuleCommands = [[NSMutableArray alloc]initWithArray:[self.serverModule.socommand allObjects]];

再次调用,我在其描述中得到两个值,一个用于原始值,一个用于编辑后的值。

任何帮助都会很棒!

~地毯嘶嘶声

最佳答案

在保存段中,您将创建一个新的 SOCommand 对象,无论它是否已存在。

为什么不直接使用实际对象(SOCommand)并编辑它们,这不会改变您的数据库信息,直到您保存上下文。
它会为您节省一些在对象之间来回交换的悲伤。

如果您无法在上下文中进行编辑,则应将现有项目 objectID 传递给您的“临时”对象,如果存在,请从数据库中获取该对象并对现有项目进行更新:< br/>

NSManagedObjectID* oID = ((SOCommandTemp*)[_serverModuleCommands objectAtIndex:j]).objectID;
if(oID) {
    SOCommand* cmd = (SOCommand*)[context existingObjectWithID:oID error:nil];
    if (cmd) { //no error fetching the object
        //update `cmd` with your new values
    }
}

关于ios - 已编辑的 UITableViewCell 正在存储为新单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20844332/

相关文章:

ios - 替换自定义键盘中预测文本的来源

ios - 使用 Floaty 库显示矩形按钮

objective-c - Objective-C - 加载表格 View 单元格时崩溃

ios - 在已经使用 SQLite 的现有应用程序中采用核心数据

ios - 在实时输入字符时,如何获取 UITextfield 的值?

ios - 图像持久化和延迟加载与 Dispatch_Async 冲突

ios - 无法共享 CKRecord

ios - 如何开发包含图片资源的iOS框架?

iphone - 如何让 CoreData Debug 参数输出到控制台?

ios - 具有关系的 CoreData NSPredicate