-2

I want to be able to use a variable in one file in another.

For example I created an array of core data items in one view controller, but I want to use it in another view controller.

Yabusa
  • 579
  • 1
  • 6
  • 15
  • 1
    The link helps you, https://stackoverflow.com/questions/5210535/passing-data-between-view-controllers – dengApro May 21 '19 at 02:08

2 Answers2

2

Core Data is to manage the model layer objects in your application. Why did you create an array of core data items in one view controller?

According to Core Data Programming Guide, you should do do initializing the Core Data Stack.

just like

class MyDataController: NSObject {
    var persistentContainer: NSPersistentContainer!

    //  ...

}


And you can fetch it in almost every file. just like :

let moc = …
let employeesFetch = NSFetchRequest(entityName: "Employee")

do {
    let fetchedEmployees = try moc.executeFetchRequest(employeesFetch) as! [EmployeeMO]
} catch {
    fatalError("Failed to fetch employees: \(error)")
}

dengApro
  • 3,848
  • 2
  • 27
  • 41
  • I have a class with three variables saved to core data. I made an array to be able to display just the titles of all the items and display them to a tableview controller. Aside from the fact they're core data. How would a variable typically be pulled from one VC to another? – Yabusa May 20 '19 at 17:38
  • I learned from a tutorial I purchased on stack skills, but I think you've made me realize I should've learned from the documentation because I don't quite understand the details – Yabusa May 20 '19 at 17:39
  • If you just want to pass data from one ViewController to another, why do you need CoreData? CoreData make you data persistent to Cache/Disk. Then you can fetch the data from anywhere. Like like UserDefaults save and fetch little data. – dengApro May 21 '19 at 02:05
1

You could create one property in ViewControllerB like this,

class ViewControllerB: UIViewController {
    var dataItems: [DataItem] = []
}

so when you navigate from ViewControllerA to ViewControllerB you could set the data to the property like below,

let viewControllerB = ViewControllerB()
viewControllerB.dataItems = [...]
navigationController?.pushViewController(viewControllerB, animated: true)

Hope this helps!

Michael Wang
  • 9,583
  • 1
  • 19
  • 17