1

I've created two arrays (imgUrl and imgTitle). I want to save these array values in Core Data. I tried like below. However, it is not successful.

//Mark:- Method to save data in local data base(CoreData)
func saveDataInLocal(imageUrl: [String], imageTitle: [String]){
    let context = CoreDataStack.sharedInstance.persistentContainer.viewContext
    let contactEntity = NSEntityDescription.entity(forEntityName: "Photos", in: context)
    let newContact = NSManagedObject(entity: contactEntity!, insertInto: context)
    for eachValue in imageTitle{
        newContact.setValue(eachValue, forKey: "imgTitle")
    }
    for eachValue in imageUrl{
        newContact.setValue(eachValue, forKey: "imgUrl")
    }

    do {
        try context.save()
        fetchData()

    } catch {
        print("Failed saving")
    }
}

XcmodelID is shown in image.

enter image description here

In these two arrays one is image title and another one image URL. Fetching I'm doing like below.

//Mark:- Method to fetch data from local database(CoreData)
func fetchData(){
    let context = CoreDataStack.sharedInstance.persistentContainer.viewContext
    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Photos")
    request.returnsObjectsAsFaults = false
    do {
        let result = try context.fetch(request)
        for data in result as! [NSManagedObject] {
            imgTitleNew.append(data.value(forKey: "imgTitle") as! String)
            imgUrlNew.append(data.value(forKey: "imgUrl") as! String)
        }
    } catch {
        print("Failed")
    }

    DispatchQueue.main.async {
        self.myCollectionView.reloadData()
    }
}

Can somebody suggest how to save the array in Core Data?

Array data displayed below.

var imgUrl = [String]() //contains urls in array
var imgTitle = [String]() //contains titles in array
rmaddy
  • 314,917
  • 42
  • 532
  • 579

1 Answers1

0

A simple solution is to save both arrays joined with tab (or other unique) characters and use computed properties for the conversion

Assuming the Core Data properties are declared as

@NSManaged public var imageURL: String
@NSManaged public var imageTitle: String

Add these two computed properties

var imageURLArray : [String] {
    get { return imageURL.components(separatedBy: "\t") }
    set { imageURL = newValue.joined(separator: "\t") }
}

var imageTitleArray : [String] {
    get { return imageTitle.components(separatedBy: "\t") }
    set { imageTitle = newValue.joined(separator: "\t") }
}
vadian
  • 274,689
  • 30
  • 353
  • 361