Accessing Dictionary outside its method

Hi, I have a view controller that includes a method to create a dictionary. I can access the items in the dictionary inside the method. But I cannot access the items outside the method even within the same view controller. I want to access the items in the dictionary to create cells in a tableview cell in another view controller.

I am missing something fundamental about how to do this and I have not been able to figure it out with numerous google searches.

Any help would be greatly appreciated.


Yes, what you’re talking about is variable scope.
When you create a variable (your dictionary) inside a method. It can only be accessed in there.

Try actually declaring the dictionary in the class (like in class ViewController)

But in your method actually populate it

Hi Mike, I had declared the dictionary in a separate class. However, it wasn’t a ViewController class. I just made it a subclass of UIViewController but I still can’t access it outside the method.

Ok, I am now able to read the dictionary values. They don’t show top the first time the button is tapped bu they show uptake second and subsequent times. Not sure why that is.

must be because your data is not called on init (viewdidload)?

Thanks Francis, so what do I have to call in viewdidload and which controller’s viewdid load?

In one controller the array of data is generated when I tap on a button, it then segues to another view controller to display the data.

why cant you just move the generation of data to the other view controller alongside displaying the data?

Hi Francis, I was thinking the same thing.

However, when I moved the generation of the data to the other view controller alongside displaying the data and then called the function from viewdidload I still get a blank tableviewcell the first time.

I then tried the override function viewwillappear with no difference.

did you try printing the data array after you called it? so you can check if the array really did populate

Yes, the first time it prints it is empty. The second time I run it and it prints it is populated.

can you post your code on how you populate it?. there must be something wrong with the order you populated your array, try switching some code around