从Array Swift 3向Core Data添加数据

时间:2017-06-08 01:00:52

标签: ios swift core-data

如果我有一个数据数组:

let  array = ["73", "24", "12", "62", "42"]

我想循环遍历数组,并将其编号添加到名为Device的实体,其属性为asset_tag,然后打印出核心数据堆栈中的值。

目前我的代码如下:

 var data: [String] = ["53","35","26","42","12"]

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

        let task = Device(context: context)

        task.asset_tag = data


        (UIApplication.shared.delegate as! AppDelegate).saveContext()


        do {
            data = try context.fetch(Device.fetchRequest())
        }

        catch {
            print ("This did not work")
        }


        print (data)

但看起来你不能将数组作为数据源添加到属性中。

1 个答案:

答案 0 :(得分:1)

花了一些时间,终于想通了。代码如下:

for device in data {

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

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