user3518271
user3518271

Reputation:

How to use same line of Code again and again in multiple view controller in ios

I am working on a MultiView application in which have a home Screen(Is Not the RootView Controller in the application). In order to pop to that Home screen I am using the following:

for (UIViewController *controller in [self.navigationController viewControllers]) {
    if ([controller isKindOfClass:[B class]]) {
        [self.navigationController popToViewController:controller animated:YES];
        break;
    }
}

Is there any way to write the above line using a Macro or something like that?
Might be this seems funny to you folks, but I am curious to know.

Upvotes: 1

Views: 104

Answers (2)

Sunny Shah
Sunny Shah

Reputation: 13020

You can use category method.

Just write one line whenever you want to use

[self.navigationController goToHome];

// interface

  @interface  UINavigationController(CustomMethod)
-(void)goToHome;
@end

// implementation

@implementation UINavigationController(CustomMethod)

-(void)goToHome{
    for (UIViewController *controller in [self.navigationController viewControllers]){
        if ([controller isKindOfClass:[B class]]){
            [self.navigationController popToViewController:controller animated:YES];
            break;}
    }
}

@end

Upvotes: 4

Rajesh
Rajesh

Reputation: 10434

Keep it in .pch file

`#define callThisMtd(B) for (UIViewController *controller in [self.navigationController viewControllers]){if ([controller isKindOfClass:[B class]]){ [self.navigationController popToViewController:controller animated:YES]; break;}}`

ad call it from any viewcontroller

callThisMtd(objB); //where objB is your B object

Upvotes: 1

Related Questions