Reputation: 416
I have a tableView, it is populated with car names. User can add, delete cells.
CarData.swift
:
struct CarData {
var name: String
}
Cars.swift
:
class Cars{
var list = [
CarData(name: "Toyota Corolla"),
CarData(name: "BMW 3")
]
}
ListViewController.swift
:
class ListViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var carsList = Cars()
var cars = [CarData]()
override func viewDidLoad() {
super.viewDidLoad()
cars = carsList.list
.
.
.
When a segue brings user to the ListViewController
, the list is always going to be the same due to the way cars
array is initialized. What I want is the list to save its data in-between segues and not to be rewritten every time. I have a lot of segues, so sending cars
array all around doesn't seem to be a great idea. What should I do?
Upvotes: 1
Views: 33
Reputation: 2275
For your begging level, you can create a singleton object to access it globally across the entire application.
class CarsManager
{
// MARK: Init
private init() { }
// MARK: Properties
static var shared = CarsManager()
private var cars: [CarData] = []
// MARK: Methods
func addNewCar(_ car: CarData)
{
cars.append(car)
}
func getCars() -> [CarData]
{
return cars
}
}
You can add cars to your list on any screen:
let someCar = CarData(name: "Toyota Corolla")
CarsManager.shared.addNewCar(someCar)
Then you can easily access your list from all screens:
CarsManager.shared.getCars()
You should read more about the pros and cons of the singleton design pattern to know when to use and when not:
Upvotes: 1