1

I don't know if it is possible, but I would like to call a view controller's method in a class object. I have method like this in my view controller's .m file:

-(void)showLeaderBoard
{
    GKLeaderboardViewController *leaderboardController = [[GKLeaderboardViewController alloc] init];
    if (leaderboardController != nil){
        leaderboardController.leaderboardDelegate = self;
        [self presentModalViewController: leaderboardController animated: YES];
    }
}

I would like to call that method in a SKScene file.

rebello95
  • 8,486
  • 5
  • 44
  • 65

1 Answers1

2

One way to do this is called delegation. In a nutshell, you allow the view controller to be the delegate on the object, so when the object wants to do something the view controller does, it can tell its delegate (the view controller) when to do it.

Step 1: Create the delegate property on the object (in the objects .h file):

// be sure to import the view controller's header here
@property (nonatomic, retain) YourViewControllerClass *delegate;

Step 2: When you create the object in your view controller, set the view controller as the objects delegate:

SKScene *theScene = // however you create your scene object here
theScene.delegate = self;

Step 3: Expose whatever method you want the object to call in the view controller's header:

- (void)showLeaderBoard;

Step 4: When you want to, tell the object's delegate to do whatever you want it to (inside the SKScene .m file):

[self.delegate showLeaderBoard];
Mike
  • 9,765
  • 5
  • 34
  • 59
  • Thanks a lot Mike! I messed with it almost half a day and still couldn't make it work. Now it's superb. (Y) – kevinmanify Aug 26 '14 at 00:06
  • Umm... One little thing more. When I configure and create new scene in another scene, how should I delegate there. "scene.delegate = self;"does not work in that case. – kevinmanify Aug 26 '14 at 01:11
  • What do you mean by create scene in another scene? – Mike Aug 26 '14 at 01:12
  • In MyScene.m file when user touches home button I create and configure scene what is actually Menu.m scene. – kevinmanify Aug 26 '14 at 01:18
  • Do you want the same delegate? You could always pass the delegate reference there, or if you want another delegate follow the same pattern as above. – Mike Aug 26 '14 at 01:18