Using the data manager to initialize ExploreItem instances

Currently, you have a data manager class, ExploreDataManager. This class contains a method, loadData(), which reads data from ExploreData.plist and returns an array of dictionaries. Next, you'll add a method that creates and initializes ExploreItem instances with that array. Follow the steps given here:

  1. In the ExploreDataManager class, add the following code above the loadData() method:
func fetch() {
for data in loadData() {
print(data)
}
}

This method will call loadData(), which returns an array of dictionaries. The for loop is then used to print the contents of each dictionary in the array to the Debug area to ensure that this method is working.

  1. Click ExploreViewController.swift in the Project navigator. Add the following to the viewDidLoad() method:
let manager = ExploreDataManager()
manager.fetch()

This creates an instance of ExploreDataManager in your app and calls its fetch() method when the app is run. Your viewDidLoad() method should look like the code given here:

override func viewDidLoad() {
super.viewDidLoad()
let manager = ExploreDataManager()
manager.fetch()
}
  1. Let's build and run your app. The contents of the ExploreData.plist file are read and printed in the Debug area. This is what the Debug area should look like:

Now, you'll assign the name and image strings from each dictionary to an ExploreItem instance.

  1. Click ExploreDataManager.swift. Add the following code just above the fetch() method:
fileprivate var items:[ExploreItem] = []

This adds a property, items, which is an array of ExploreItem instances, to ExploreDataManager and assigns an empty array to it.

  1. Inside the fetch() method, replace the print() statement with the following:
items.append(ExploreItem(dict: data))

This assigns the name and image strings in each dictionary read from ExploreData.plist to the name and image properties of an ExploreData instance, and adds that instance to the items array.

Our completed ExploreDataManager class should look like this:

import Foundation

class ExploreDataManager {

fileprivate var items:[ExploreItem] = []

func fetch() {
for data in loadData() {
items.append(ExploreItem(dict: data))
}
}

fileprivate func loadData() -> [[String: AnyObject]] {
guard let path = Bundle.main.path(forResource: "ExploreData",
ofType: "plist"),
let items = NSArray(contentsOfFile: path) else {
return [[:]]
}
return items as! [[String:AnyObject]]
}
}

At this point, you have an ExploreDataManager class that reads data from ExploreData.plist and stores it in items, an array of ExploreItem instances. The next step is to provide that data to the collection view managed by ExploreViewController so it will be visible on the screen.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.232.189