简体   繁体   中英

How to save String Array to Core Data in Swift

I need to save my String Array to Core Data.

let stringArray: [String] = ["First String", "Second String", "Third String"]

I have 1 Attributes with the type String. I have tried that, but it doesn't work.

let entityCoreData = NSEntityDescription.insertNewObject(forEntityName: "Hadith", into: context)

entityCoreData.setValue(firstEntity, forKey: "firstAttribute")

do {
    try context.save()
} catch {
    print("issue by saving data")
}

Add Entity in .xcDataModel as "Hadith" & add 1 attribute as "value" type of string.
Now select that entity & from Editor Menu -> Create NSManagedObject class

Save data in entity

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let context = appDelegate.managedObjectContext

    for str in strinArray {
        do {
            let newitem = NSEntityDescription.insertNewObjectForEntityForName("Hadith", inManagedObjectContext: context)
            newitem.setValue(str,forKey: "value")
            try context.save()
        } catch {
            //do nothing
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM