1

If I have an array of data for instance:

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

And I would like to loop through the array and add its number to my entity called Device with attribute asset_tag and then print out the values from my core data stack.

Currently my code is as follows:

 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)

but it doesn't look like you can just add an array as the source for data into an attribute.

4
  • Do you want to create 5 devices with one attribute respectively or 1 device ? Anyway the array is an array of strings, why do you annotate it as most unspecified [Any]? Commented Jun 8, 2017 at 4:01
  • I would like to enter 5 devices, each device would be a different asset tag number. Commented Jun 8, 2017 at 23:22
  • Then no, you can't do it this way. You need a repeat loop to create the 5 devices. Commented Jun 9, 2017 at 4:04
  • Device(context: context) is a custom method. I have no idea what it does exactly. Otherwise (pseudocode) : for tag in data { let device = create_the_device(); device.asset_tag = tag } save_the_context() Commented Jun 9, 2017 at 20:13

1 Answer 1

1

Spent some time and finally figured it out. Code is as follows:

for device in data {

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

            newArray.setValue(device, forKey: "asset_tag")
        }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.