1

Is it possible to call a method (written in a Gamescene) from a ViewController in Swift? I read about Protocol, delegate or Inheritance but all tutorials I saw don't show this case.

Thank you for your help.

Haox
  • 576
  • 6
  • 21

2 Answers2

1

try this.

in ViewController class

#import "Gamescene.h"

Gamescene *obj = [[Gamescene alloc] init];

[Gamescene methodName];

and don't forgot to add method name in Gamescene.h file..

in Swift

class SomeClass {
    class func someTypeMethod() {
    // type method implementation goes here
}

}

SomeClass.someTypeMethod()

you can learn here apple Documentation.

hmdeep
  • 3,005
  • 3
  • 12
  • 22
  • I code in swift. I saw there isn't import statement. Is there a difference in the code ? – Haox Oct 13 '14 at 11:33
  • I tried that : `GameScene.startTimer()` but I have a message error : "missing argument for parameters #1 in call" – Haox Oct 13 '14 at 13:45
  • is startTimer() method has any parameter to pass?i mean any input needed to pass in this method? – hmdeep Oct 14 '14 at 04:03
0

There's following way you can call a method,

  • If a method is in your view controller it self then, you can call it with self, check question for help, How can I call a method in Objective-C?

    [self yourMethodName];

    If its a class method then, [ClassName yourMethodName];

  • If your method is from other class, just #import that class like #import "someclass.h" then same, create a object of that class and call, check this for more help, Objective C - Call method from another class

    someclass *obj = [[someclass alloc] init];

    [obj methodName];

    If its a class method then [someclass methodName]; check question for help, calling class methods objective c

  • with delegate, if you've self delegate for someclass then in someclass you can call it like this, check question, How do I create delegates in Objective-C?

    if(self.delegate && [self.delegate respondsToSelector(methodName)]) { [self.delegate methodName]; }

    and in your view controller you've to write like this,

    someclass *obj = [[someclass alloc] init]; obj.delegate = self;

    - (void)methodName { //call when delegate calls it. }

  • Anothe way is with NSNotificationCenter, see this question for detail help, Send and receive messages through NSNotificationCenter in Objective-C?

Community
  • 1
  • 1
Hemang
  • 25,740
  • 17
  • 113
  • 171