Learn Courses My Dashboard

Calling from one view controller to another - problem

Hey guys, I am having a problem with my macOS code, I am attempting to call a function that is in View controller 1 from a function in View Controller 2.

I populate the parameter ‘int’ in VC 2 but when it gets to VC 1 it throws a fatal error for unexpectedly finding nil. However due to the fact that the error is generated on different line of VC1 every time means that the variable ‘int’ does have a value and therefore should not be nil.
why is the code doing this?

any help you all could give would be great.

Thanks. Terry Baillie

Hi Terry we mostly do iOS, not MacOS, btw, so we may not always be able to help with MacOS questions.

But this one might be fine.

I’d personally use the delegate/protocol pattern.

I’d also set this up differently. You could just pass C.L1CardBuy directly to your function Collection.OwnedCardDisplay Because you’re using the same number

But you shouldn’t be calling Collection.OwnedCardDisplay Like this usually (unless the function is static.

You’re basically trying to initialize and call that function together, but is this the place where you want to initialize this new VC??? Usually you declare the VC and will then call a function or pass a value to VC 2

I declared the VC at top above the class by adding this - var Collection = CollectionView()

The function that asks for the int parameter is in this VC.

The VC that has the func to supply the value to the collection VC called StoreView.

The purpose of this whole set up is that when I’m in the Store view I have the opportunity to buy “cards” I’m trying to tell the system that I bought one and therefore send the information to the collection view to show that card has been purchased now.

I’m not sure what you mean about protocols in your answer but I’ll research that idea. Thank you so much.

Protocol / delegate pattern is very common in iOS dev, I’m not sure about MacOS, to pass data around.

What you really should be doing is saving data that you’ve bought a card in a database or something, and the collection view side fetches that data.

Also just a side note: your variables should NOT begin with a capital letter. That’s not proper Swift convention and is confusing to others who may read your code, and even if it is your own project, you still should try to follow proper conventions as much as you can.

Thank you so much. And noted on variable capitalization problem I have.

1 Like