将两行数据插入Core Data Swift 3

时间:2017-06-12 03:20:04

标签: ios arrays swift core-data

我有一个核心数据堆栈,其中有一个名为Device的实体,它有两个属性,asset_tag和location。我有两个我这样设置的阵列:

var assetTag = ["53","35","26","42","12"]
var location = ["SC", "FL", "NA", "NY", "CF"]

我的代码的第一部分循环遍历第一个数组,并将每个数字添加到asset_tag属性中,如下所示:

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

  for device in assetTag {

        let newArray = NSEntityDescription.insertNewObject(forEntityName: "Device", into: context)

        newArray.setValue(device, forKey: "asset_tag")
    }

这会将每个值添加到数组中,以便稍后将其打印出来,这样可以完美地运行。我想对第二个数组做同样的事情,并将它们添加到我的第二个属性,但是当我尝试时,它没有正确添加数据。这就是我所拥有的:

for locations in location {

            let secondArray = NSEntityDescription.insertNewObject(forEntityName: "Device", into: context)

            secondArray.setValue(locations, forKey: "location")

        }

当我打印出结果时,我得到了一堆nill值:

[<Device: 0x600000281130> (entity: Device; id: 0xd000000001580000 <x-coredata://22AC91EB-92B1-4E5B-A5A9-A5924E0ADD3E/Device/p86> ; data: {
    "asset_tag" = nil;
    devices = nil;
    location = CF;
}), <Device: 0x60000009f040> (entity: Device; id: 0xd0000000015c0000 <x-coredata://22AC91EB-92B1-4E5B-A5A9-A5924E0ADD3E/Device/p87> ; data: {
    "asset_tag" = 53;
    devices = nil;
    location = nil;
}), <Device: 0x6000002810e0> (entity: Device; id: 0xd000000001600000 <x-coredata://22AC91EB-92B1-4E5B-A5A9-A5924E0ADD3E/Device/p88> ; data: {
    "asset_tag" = nil;
    devices = nil;
    location = NY;

我不确定那些来自哪里。

修改

看起来更好但我得到另一个名为Devices with nils的属性:

  "asset_tag" = 12;
    devices = nil;
    location = CF;

同样,当我从上面的核心数据中打印出结果时,值的顺序与我定义数组的顺序不一样。

"asset_tag" = 12;
    devices = nil;
    location = CF;

  "asset_tag" = 53;
    devices = nil;
    location = SC;

上面的结果显示12然后是53和CF然后是SC,但这与设置的原始数组的顺序不同。

1 个答案:

答案 0 :(得分:1)

您必须创建5个具有2个属性的实例。您的代码将创建10个不同的实例。核心数据实体就像一个具有多个属性的类。

解决方案是使用基于索引的循环并分配两个属性。

为了更好地理解核心数据实例device而不是newArray。以下代码使用数组来保留实例。

assert行是检查两个数组是否包含相同数量的项目。

var devices = [Device]()

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

assert(assetTag.count == location.count, "Both arrays must have the same number of items")
for i in 0..<assetTag.count {

    let device = NSEntityDescription.insertNewObject(forEntityName: "Device", into: context) as! Device

    device.asset_tag = assetTag[i]
    device.location = location[i]
    devices.append(device)
}

旁注:

声明在Core Data模型中应该具有非可选值的字符串属性。