Richard Topchii
Richard Topchii

Reputation: 8215

Objective-C category calling method of a custom class

I have some classes, lets call them A, B and C, being inherited from UIViewController and some category of UIViewController that has some methods in it that have to be common for all the classes.
Category's methods have to call another methods on ViewControllers, but. Not all methods will be implemented in VCs (because they never be called in that context).
If I write method definition in category, I get an error, that method is not declared, but it is declared in VC or not declared and will never be used in that context.
Is there any ideas how to override this and share huge part of code (Navigation code) between multiple ViewControllers?

- (void)homeButtonPressed {
    NSLog(@"Home button pressed, ViewController");
}

- (void)changeFloorButtonPressed {
    [self changeFloor];
    NSLog(@"Change Floor button pressed, ViewController");
}
- (void)QRButtonPressed {
    NSLog(@"QR button pressed, ViewController");
}  

Here [self changeFloor]; is method, which is specific only to one ViewController.

Upvotes: 0

Views: 1086

Answers (2)

Justin Holman
Justin Holman

Reputation: 852

Why note create your base class of type UIViewController, then create classes that inherit from your new base class. Each child can then implement the methods they need.

MyBaseViewController: UIViewController

ViewAViewController: MyBaseViewController

ViewBViewController: MyBaseViewController

etc

I use this type of approach for universal apps, my child class can override the implementation from the parent or add to it.

// common elements HomeViewController: UIViewController

// iPhone specific implementation HomeViewController_iPhone : HomeViewController

// iPhone specific implementation HomeViewController_iPad: HomeViewController

Upvotes: 1

Nick
Nick

Reputation: 2369

Create an objective-c protocol which declares an @optional method for -(void)changeFloor; Then, in your category, conform to that protocol. You will be able to call the changeFloor method without getting a compile error.

Because the method is optional, you must check if:

[self respondsToSelector:@selector(changeFloor)] before calling changeFloor.

edit: there is probably a way to architect your code so that you don't need to do this.

Upvotes: 1

Related Questions