ios - 在遍历数组时保存到 CoreData

标签 ios swift core-data

<分区>


这个问题是由于错别字或无法再重现的问题引起的。虽然类似的问题可能是on-topic在这里,这个问题的解决方式不太可能帮助 future 的读者。

已关闭 7 年前

从 Web 服务下载后,我得到了这个字符串 "85:ABC ,83:CFD"。我需要将这些值存储到 CoreData 表 TABLE_JOBTITLE。我有以下代码

var designationDictionaryArray = results.componentsSeparatedByString(",")

var index: Int = 1
        for item in designationDictionaryArray
        {
            let appDelegate =
                UIApplication.sharedApplication().delegate as! AppDelegate

            let managedContext = appDelegate.managedObjectContext


            let entity =  NSEntityDescription.entityForName("TABLE_JOBTITLE",
                                                            inManagedObjectContext:managedContext)

            let job = NSManagedObject(entity: entity!,
                                      insertIntoManagedObjectContext: managedContext)

            job.setValue(String(index), forKey: "column_Id")
            job.setValue(String(item.componentsSeparatedByString(":")[0]), forKey: "column_Server_Id")
            job.setValue(String(item.componentsSeparatedByString(":")[1]), forKey: "column_Job_Name")

            print("Column_Id")
            print(index)
            print("Column_Server_Id")
            print(String(item.componentsSeparatedByString(":")[0]))
            print("column_Job_Name")
            print(String(item.componentsSeparatedByString(":")[1]))


            do {
                try managedContext.save()
                print("saved job title")
            } catch let error as NSError  {
                print("Could not save \(error), \(error.userInfo)")
            }

            self.desiginationArray.append(item.componentsSeparatedByString(":")[1])
            index = index + 1
        }

我能够遍历每个数据,但是当我将它存储在表中时......它的存储方式如下

coulmn_Id          column_ServerId    column_Job_Title              
1                        83                  CFD
1                        83                  CFD

有人可以帮我纠正代码或解释这种奇怪行为的原因吗?

最佳答案

我怀疑以下两件事之一:

  1. 结果中的值与您预期的不一样。
  2. 您检查输出的方式有误。

我倾向于后者,因为我看不出有任何方法可以在单次运行中为两个实体分配相同的列 ID。

在顶部放置断点以检查结果的值和从 results.componentsSeparatedByString(",") 返回的数组。

显示您用来遍历表以检查它的代码。我敢打赌你没有显示真实的输出。循环中打印行的输出是什么?如果它看起来像这样:

Column_Id
1
Column_Server_Id
85
column_Job_Name
ABC
Column_ID
2
Column_Server_ID
83
Column_ID
CFD

那么我肯定会说,您没有正确地从 Core Data 回读结果。让我们看看您是从哪里获得决赛 table 的。

关于ios - 在遍历数组时保存到 CoreData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36371827/

上一篇:ios - 无法获取 UIView 的 subview

下一篇:ios - NSInvalidArgumentException 与使用 JSQMessagesViewController

相关文章:

iOS 使用 OAuth 连接到 Magento

ios - 在图像中添加 MKPointAnnotation 时蓝点未移除

ios - 从 CNContactPicker 中的单个联系人中选择多个属性

ios - 如何使用 SwiftUI 在 tvOS 中垂直滚动?

ios - 接收者类型是前向声明

objective-c - 代码中添加的UIButton无法响应触摸

ios - 由于 swift 版本 3,ionic 4 ios 无法构建

Swift:多次循环后更改随机数的算法

cocoa - 在 TableView 中显示多对关系

Xcode-错误 : pathspec '...' did not match any file(s) known to git