1

I've been recently trying to migrate my app into an MVC format and I was wondering how one would go about accessing a View Controller's variables (trying to access them FROM a .swift file) without having to create a new instance of the View Controller. For example:

HomePageViewController().objectIDs.append(post.objectId!)


HomePageViewController().postTitles.append(post["Title"] as! String)


HomePageViewController().imageFiles.append(post["imageFile"] as! PFFile)


HomePageViewController().descriptions.append(post["description"] as! String)


HomePageViewController().userNames.append(post["originalPosterUserName"] as! String)


HomePageViewController().numOfComments.append(String(describing: post["numberOfComments"]!))


print(HomePageViewController().userNames, "This is a test")

The print statement at the end prints '[]This is a test' with no data inside of the array. Inside of the HomePageViewController file, this works perfectly though. I'm assuming that this isn't working due to me creating a new instance of the HomePageViewController and altering THOSE variables rather than the current one. So, my question is, how would I be able to alter the variables of the current HomePageViewController without the need to create a new instance?

A solution like this wouldn't work either since I have multiple classes with the same variable names.

I'd appreciate any help. Thanks!

1
  • View controllers are not supposed to access data from anywhere other than a model. Commented Mar 14, 2017 at 22:23

1 Answer 1

2

If you're implementing MVC, the data you wish to be share across multiple view controllers should be contained in the model, and either instantiated as a singleton and accessed globally (as with UserDefaults) or passed from one controller to the other as a parameter when you present the new VC.

By definition, View Controllers should not be accessing each others' variables.

Sign up to request clarification or add additional context in comments.

3 Comments

Ok, makes sense. So, the variables should reside in the model class and I should access them from the View Controller file in order to update/manage the UI?
That's correct. You can access them explicitly in code, or using KVO. Hope my answer helped.
Yep, that cleared it up for me. Thanks for the help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.