0

Let me first frame my situation. I have a ViewController, which retains an instance of a GameManager. The GameManager class encapsulates the state and logic of a simple game. When certain states are encountered in the GameManager, I would like to perform a set of actions. For instance: when a game is over, I would like to display a game over dialog. As mentioned above, the game logic resides in the GameManager, but the method to create and position a new 'game over' dialog resides in the ViewController. To allow for the GameManager to 'call' back into the ViewController, I passed a reference to the ViewController to the GameManager when allocated, and simply invoke methods on the ViewController. For example:

// GameManager.m
- (void) gameOver {
    [self.viewController showGameOver];
}

My question is: Is this the proper, objective-c way to do this? Is there a purer way to handle this? I've though using blocks may be more appropriate.

  • 1
    Not necessarily your question, but make sure that you have a `weak` attribute on that `self.viewController` reference. Otherwise, because `viewController` holds on to `gameController` and `gameController` holds on to `viewController` neither will let go and you'll get memory leaks. – Logan Jun 08 '14 at 20:33
  • Thanks for the tip. I figured the same. – user3720455 Jun 08 '14 at 23:19

1 Answers1

0

Implement a delegation pattern here

In your GameManager

@protocol MyGameDelegate : <NSObject>

@required

- (void)gameManager(GameManager *)gameManager gameOverWithSuccess:(BOOL)success;

@end

and declare a property

@property (assign, nonatomic) id <MyGameDelegate> gameDelagate;

in your viewContoller class

//  MyGameDelegate implementation

- (void)gameManager(GameManager *)gameManager gameOverWithSuccess:(BOOL)success {

    if (success) [self.viewController showGameOver];
}

do something like this but be careful

@property (assign, nonatomic) id <MyGameDelegate> gameDelagate;

there you are not using strong

Finally set gameDelagate as your viewcontroller

hope you have understood.

Goppinath
  • 10,569
  • 4
  • 22
  • 45
  • This is great. I really appreciate the explanation. It works as is now, but I'm always looking for the most appropriate way to handle things. This really helps. – user3720455 Jun 08 '14 at 23:21