Mind Pixel
Mind Pixel

Reputation: 814

How to navigate to a ViewController from NSObject Class in iOS?

I am facing a problem from last week. My requirement is, I have to create a custom NSObject class in which I have to write all navigation method for all button Click action. And when I click a button, the button action will retrieve navigate method from that custom NSObject class according to click & navigate. But it's Not working. What I am implementing, I share my code below:

This is my Method_Action_class.h Class

   #import <Foundation/Foundation.h>
   @interface Method_Action_class : NSObject
   -(void)login_method_called;
   @end

This is my Method_Action_class.m Class

   #import "Method_Action_class.h"
   #import "Home_ViewController.h"

   @implementation Method_Action_class

   -(void)login_method_called
   {
       UIWindow *window=[UIApplication sharedApplication].keyWindow;
       Home_ViewController *home = [[Home_ViewController alloc] initWithNibName:@"Home_ViewController" bundle:nil];
       [window.rootViewController.navigationController pushViewController:home animated:YES];

   }
   @end

When I call this method on Button click:

   #import "Method_Action_class.h"

   Method_Action_class *demo = [[Method_Action_class alloc] init];
   [demo login_method_called];

Note: Method_Action_class is my NSObject type class

Here code is running successfully without warning/Error, but not navigate to another class.

Please help me.

Upvotes: 0

Views: 1552

Answers (2)

Soumya Ranjan
Soumya Ranjan

Reputation: 4843

In your button click action You have to send your UINavigationController & current ViewController. Because NSObject class not found that controller.

In your Button Action put this Code:

[demo login_method_called:self.navigationController withCurrentViewController:self];

In your NSObject .h class put this code:

#import <Foundation/Foundation.h>
#import "Home_ViewController.h"

@interface Method_Action_class : NSObject

- (void)login_method_called:(UINavigationController*)navigation  withCurrentViewController:(UIViewController*) controller;
@end

In your NSObject .m class put this code:

#import "Method_Action_class.h"

@implementation Method_Action_class

-(void)login_method_called:(UINavigationController*)navigation  withCurrentViewController:(UIViewController*) controller
{
   Home_ViewController *home = [[Home_ViewController alloc] initWithNibName:@"Home_ViewController" bundle:nil];
   [navigation pushViewController:home animated:YES];
}
@end

And Build your code, It's navigate successfully. :)

Upvotes: 2

ashForIos
ashForIos

Reputation: 399

Please use NSNotificationCenter and use PushView from that controller.Or u can use Custom Delegate.For this u can refer

[1]: https://stackoverflow.com/questions/2191594/send-and-receive-messages-through-nsnotificationcenter-in-objective-c

Upvotes: 2

Related Questions