2017-06-12 9 views
0

我有一个核心数据堆栈,它由一个名为Device的实体组成,其中包含两个属性asset_tag和location。我有已经设置了这样两个阵列:将两行数据插入Core Data Swift 3

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; 

我不知道在那些尼尔斯的来源。

编辑:

这看起来更好,但我得到所谓的设备与尼尔斯另一个属性:

"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

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

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

为了更好地理解,将Core Data实例命名为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) 
} 

旁注:

申报字符串属性,这些属性都应该有一个价值作为核心数据模型非可选。

+0

我添加了一个编辑到我原来​​的帖子,我仍然有一些问题。此外,我无法使用device.asset_tag,但我有Xcode使我的管理对象的子类。不知道为什么它不让我使用device.asset_tag, – Martheli

+0

'devices'是'nil',因为没有设置属性。请记住,您只需在重复循环中设置“asset_tag”和“location”的属性。该集合默认情况下是无序的。当您使用提取请求读取对象时,您可以传递一个排序描述符来强制执行特定顺序。我更新了答案,以便能够使用点符号来表示属性。 – vadian

+0

是的,但设备不是我的数据模型中的属性,我不确定它来自哪里。 – Martheli

相关问题