IOS Swift - How to store an array using Core Data?

I am new to iOS development and wanted to know what data type I should specify for storing several rows (array). The application should do with food, and I need to store several ingredients as a single attribute.

I was thinking of making the ingredient an entity, but I just want to make the starter easier. I read about a convertible type, but people don't seem to recommend using it to store arrays.

+6
source share
4 answers

Warning: stubborn answer ahead.

No.

Storing things in an array doesn't make it easy for you. On the contrary, it will make things a lot more difficult for just an hour. Imagine that you want to show all recipes containing the selected ingredient. It will not be easy with your hacking of the array, with the appropriate model it is just a couple of lines of code.

I would recommend using a good old relationship with Join-entity.

basic recipe data model

Yes, it's harder than hacking something together that barely works. But this is the right way.

+12
source

What you were thinking about is exactly what you should be doing. Master data is created to store values ​​in an array structure. You must create the Ingredients entity and connect your Food object (or whatever you would like to name) with the relation to the Ingredients component.

+2
source

there is a way. You can execute each item manually, for example. You have an array:

let employee: NSMutableArray = [] employee.addObject(["name":"Bill","LastName":"Hanks"]) employee.addObject(["name":"Rolex","LastName":"Swarzer"]) employee.addObject(["name":"Clive","LastName":"Martin"]) employee.addObject(["name":"Jimi","LastName":"Hendrix"]) 

Assuming you created your coreData with Entity "Employee" and the attributes "name" and "lastname", you do the following to add it to ...

 let appDel = UIApplication.sharedApplication().delegate as! AppDelegate let context = appDel.managedObjectContext for item in employee { do { let newUser = NSEntityDescription.insertNewObjectForEntityForName("Employee", inManagedObjectContext: context) newUser.setValue(item["name"], forKey: "name") newUser.setValue(item["LastName"], forKey: "lastname") try context.save() } catch { //do nothing } 

You can then retrieve all the elements using a select query or an NSFetched Results controller

+1
source

I did in Swift 4,

Storing more arrays in allDataArray (one array). Retrieving array objects from CoreData (AllData) and displaying in TableView

 import UIKit import Foundation import CoreData class ViewController: UIViewController { var allTableDataArray : [AllData] = [AllData]() let allDataArray : NSMutableArray = [] var listOfArray1 = ["#849578", "#849302"] var listOfArray2 = ["Vasuki Shiv", "Prathap Dusi"] override func viewDidLoad() { super.viewDidLoad() saveAllDataToCoredata() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) fetchAllDataFromCoredata() } func saveAllDataToCoredata() { deleteAllData(entity: "AllData") let context = PersistenceSerivce.context allDataArray.add(["requestNo" : listOfArray1[0], "vendorName" : listOfArray2[0]]) allDataArray.add(["requestNo" : listOfArray1[1] , "vendorName" : listOfArray2[1]]) for item in (allDataArray){ do { let newUser = NSEntityDescription.insertNewObject(forEntityName: "AllData", into: context) guard let requestNoNew = item as? [String:Any] else { return } let requestNoStr = requestNoNew["requestNo"] as! String newUser.setValue(requestNoStr, forKey: "requestNo") guard let vendorNameNew = item as? [String:Any] else { return } let vendorNameStr = vendorNameNew["vendorName"] as! String newUser.setValue(vendorNameStr, forKey: "vendorName") PersistenceSerivce.saveContext() try context.save() } catch { //do nothing } } } func fetchAllDataFromCoredata(){ let context = PersistenceSerivce.context let fetchRequest = NSFetchRequest<AllData>(entityName: "AllData") allTableDataArray.removeAll() do { allTableDataArray = try context.fetch(fetchRequest) } catch { print("Unable to fetch from Coredata", error) } } func deleteAllData(entity: String) { let managedContext = PersistenceSerivce.context let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entity) fetchRequest.returnsObjectsAsFaults = false do { let results = try managedContext.fetch(fetchRequest) for managedObject in results { let managedObjectData:NSManagedObject = managedObject as! NSManagedObject managedContext.delete(managedObjectData) } } catch let error as NSError { print("Delete all data in \(entity) error : \(error) \(error.userInfo)") } } } //MARK:- UITableView extension ViewController : UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 44 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (allTableDataArray.count) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: 'TableViewCellID') as? TableViewCell let allData = allTableDataArray[indexPath.row] cell?.requestNoLabel.text = allData.requestNo cell?.vendorNameLabel.text = allData.vendorName return cell! } } 
0
source

Source: https://habr.com/ru/post/983737/


All Articles