This a very basic question but I’ve searched all over and been unable to find an answer that explains well enough for me to get my head around it.
What I want to do is create a method in one class of my iOS app and then call that method from other classes in my app. Could someone explain exactly what I need to do to achieve this? Any help would be greatly appreciated as all my attempts so far have failed!
Thanks.
Objective-C:
You have to import the header of the class that contains the method you want to use (ClassYouWantToUse.h) into the class you want to use it at (TargetClass).
Inside the TargetClass.h or TargetClass.m (depending on the scope you want to give it):
Then create an instance of the class you want to use inside the target class either as a property like this:
Or as an instance variable like this:
Make sure you initialize it! (usually inside ViewDidLoad):
Now you can call any public methods from that class like this:
Note: The ClassYouWantToUse class must have the methods that you want to make accessible to others by declaring them in the header file:
Otherwise you won’t be able to see these methods.
Swift:
Theres really nothing special about it in swift, just adding this as a reference.
In swift you simply create an instance of the class you want to use:
And use it directly: