How do I reference fields in a self defined NSObject?

108 Views Asked by At

Looking for assistance since I am missing something! I have defined a new object called "User".

class User: NSObject {

    var userID: String!
    var fullname: String!
    var imagePath: String!
}

Now I want to iterate through each object one at a time checking the values of some of the fields.

func retrieveUsers() {
        let ref = Database.database().reference()
        ref.child("users").queryOrderedByKey().observeSingleEvent(of: .value, with: { (snapshot: DataSnapshot) in
            let users = snapshot.value as! [String: AnyObject]
            self.user.removeAll()
            
            for (key,value) in users {
    // HOW DO I REFERENCE A FIELD IN THE USER OBJECT
            }
          }
1

There are 1 best solutions below

5
jnpdx On

Keep in mind that in your code, your users object is of type [String:AnyObject] since you're grabbing it from a database (Firebase?).

So, you have an untyped Dictionary to deal with.

You can reference fields on the dictionary by doing users[key] where key is a String.

Judging by your naming of variables, it looks like you're expecting users to be an array rather than a dictionary, but then you're casting it as a dictionary. Without knowing your database schema it's hard to say what's actually happening.

But, you most likely want to actually turn your [String:AnyObject] into your actual data type. There are a number of approaches to this, but you may have to write your own decoder.

You may want to add more information about what database you're actually using.

Update: Including an example method for turning your dictionary into your object:

class User: NSObject {
    var userID: String
    var fullname: String
    var imagePath: String

    required init(withDictionary dict : [String: AnyObject]) {
        userID = (dict["userID"] as? String) ?? ""
        fullname = (dict["fullname"] as? String) ?? ""
        imagePath = (dict["imagePath"] as? String) ?? ""
    }
}

Note that I'm not handling failures -- just putting in empty strings.

You can also look into storing making your model Codable compliant and try to convert in and out of JSON. See: How can I use Swift’s Codable to encode into a dictionary?