turbs
turbs

Reputation: 85

User Class Design

I am very new to design patterns, so I am in need of help determining a good way of designing a specific part of an iOS app I am working on.

I have a User object, that represents the user that is logged in. It is very simple, and looks like this:

class User {
    var firstName: String
    var lastName: String
    var photo: String //must be stored as a string for the filename.
    var listOfJoinedOpportunities = [Opportunity]()
    var listOfJoinedOpportunitiesKeys = [String]()
    var listOfFriendsOnTheApp: NSArray
    var bio: String
    var email: String
    var userID: String   //A unique ID that is used to persist data about the user to the database (Firebase). 


  init(firstName: String, lastName: String, photo: String, email:String, userID: String, joinedEvents: [Opportunity],joinedStrings: [String]){
    self.firstName = firstName
    self.lastName = lastName
    self.photo = photo
    self.listOfJoinedOpportunities = joinedEvents
    self.listOfFriendsOnTheApp = []
    self.listOfJoinedOpportunitiesKeys = []
    self.bio = ""
    self.email = email
    self.userID = userID
  }   
}

Currently I am only in need of an instance that represents the logged in user, but I could foresee needing this class if I add features to interact with other users of the app.

A total of 5 views include interactions that need to read and write to the user object that represents the logged in user.

Currently, I am passing around the object from controller to controller by creating new references. OR, I am creating a new object that represents the same logged-in user from data that was saved to the database (Firebase).

Please help!

Upvotes: 2

Views: 1932

Answers (1)

Mark McCorkle
Mark McCorkle

Reputation: 9414

Passing the object to the destination view is actually the preferred way to handle this (prepareForSegue). That being said, you can also simply store the User object instance in your AppDelegate and reference it from any view easily if that fits your model.

The drawback to storing references in the App Delegate is clutter and it may be unnecessary in more complex cases since they'll always be allocated (lookup lazy loading as well). Generally you want to pass objects along so the previous views can dealloc which in turn lowers your memory footprint. This way if you receive a memory warning you can handle it appropriately to recover properly.

// Set a var in your appDelegate
var user:User?

// Accessing it from any view
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let loggedInUser = appDelegate.user

Upvotes: 1

Related Questions