Load items from a plist

0

I'm having trouble loading the items on a property list. Note my plist:

Here'smyfirstViewController:

importUIKitclassPage1:UITableViewController{varfilePath:String?varemployees:[[String:Any]]=[]overridefuncviewDidLoad(){super.viewDidLoad()self.tableView.delegate=selfself.tableView.dataSource=selffilePath=Bundle.main.path(forResource:"directory", ofType: "plist")
    employees = NSArray(contentsOfFile: filePath!) as! [[String: Any]]

    for item in employees {

        print(item["Name"] as Any)
        print(item.count)
        print(employees.count)
    }
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return employees.count
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destination = segue.destination as? Page2,
        let indexPath = tableView.indexPathForSelectedRow {
        destination.itemSelecionado = employees[indexPath.row]
        tableView .deselectRow(at: indexPath, animated: true)
    }
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
    cell.nameLabel.text = (employees[indexPath.row]["Name"] as! String)
    cell.positionLabel.text = (employees[indexPath.row]["Position"] as! String)

        return cell
    }
}

Here's my second View Controller:

import UIKit

class Page2: UITableViewController {

var itemSelecionado: [Page1] = []

override func viewDidLoad() {
    super.viewDidLoad()

    self.tableView.delegate = self
    self.tableView.dataSource = self
}

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return itemSelecionado.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell2
    cell.emailLabel.text = (itemSelecionado.employees[indexPath.row]["Email"] as! String )
    cell.phoneLabel.text = (itemSelecionado.employees[indexPath.row]["Phone"] as! String? )

    return cell
    }   
}

Xcode is returning me 3 errors, they are:

However,Idonotunderstandthereasonfortheseerrors,couldanyonehelpme?

Thanksinadvance!

Problemtryingtoinsertimage:

    
asked by anonymous 26.03.2017 / 04:12

2 answers

2

The problem is that you are trying to access an internal property of your view controller Page1 in the ViewController Page2. If you need to access a variable in a global way it does the following:

Create a structure to group your "global" (shared) variables and add a static property instance , declare your employees array and other properties you think necessary.

struct Shared {
    static var instance = Shared()
    var employees: [Employee] = []
}

Create a structure with a custom init to make it easier to create your structures:

struct Employee {
    let position: String
    let name: String
    let email: String
    let phone: String
    init(dictionary: [String: String]) {
        self.position = dictionary["Position"] ?? ""
        self.name = dictionary["Name"] ?? ""
        self.email = dictionary["Email"] ?? ""
        self.phone = dictionary["Phone"] ?? ""
    }
}

So you can read the plist within the didFinishLaunchingWithOptions method in your AppDelegate class:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    if let url = Bundle.main.url(forResource: "directory", withExtension: "plist"), let array = NSArray(contentsOf: url) as? [[String: String]] {
        Shared.instance.employees = array.map{Employee(dictionary: $0)}
    }
    return true
}

And view the employees in any view controller:

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        Shared.instance.employees.forEach({
            print("name:", $0.name)
            print("position:", $0.position)
            print("phone:", $0.phone)
            print("email:", $0.email)
            print()
        })
    }
}
    
26.03.2017 / 15:25
0

I have been able to solve those problems, but now others have emerged. I am not able to receive the data in my TableViewController.

I've done this: I first created a variable to receive Struct Shared :

var item1: Shared!

After defining the numberOfSections and the numberOfRowsInSection , I think I put some incorrect information in dequeueReusableCell . But I do not know what it was. Here's what I did:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
    cell.nameLabel.text = (item1.employees[indexPath.row]["Name"] as? String)
    cell.positionLabel.text = (item1.employees[indexPath.row]["Position"] as? String)

In the last two lines below it reports:

Type 'Employee' has no subscript members

I could not identify what I put in the wrong.

    
26.03.2017 / 20:28