Tina
Tina

Reputation: 31

How to push next class without class name instead of using NSString in iOS?

I have many class like Page1 , Page2, Page3, Page4, Page5 ..............

I want to write one method to go to the next class and it will call Page1,2,3 according to my need.

Here is my code what I am doing:

 for (int j = 0; j<5; j++) {

    NSString *str_varForPage = [NSString stringWithFormat:@"%i", j];

    if ([txt_Chapter.text isEqualToString:str_Chapter] && [txt_Page.text isEqualToString:str_varForPage]) {

        NSString *Str_Page = @"Page";
        NSString *Str_NextPage = [NSString stringWithFormat:@"%@%@", Str_Page , str_varForPage];
        NSLog(@"Str_NextPage is: %@",Str_NextPage);


        Str_NextPage *nextclass= [[Str_NextPage alloc]initWithNibName:nil bundle:nil];       // error  Crash  , I want to call Page0 to Page4 classes here according to my need.
        [self.navigationController pushViewController:nextclass animated:YES];
    }

Any idea or suggestion would be highly welcome.

Upvotes: 0

Views: 85

Answers (3)

Harunmughal
Harunmughal

Reputation: 367

//if you want to switch specific viewController With Storyboard, You can use like this:-

LargeImageView *largeImageViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"LargeImageView"];

  [self.navigationController pushViewController:largeImageViewController animated:YES];

//if you want to switch specific viewController With out using storyboard, You can use like this:-

MasterViewController *masterVC = [[MasterViewController alloc] initWithNibName:@"MasterViewController" bundle:nil];
    [self.navigationController pushViewController:masterVC animated:YES];

//if you want to switch specific class, You can use like this:-

NSString *movePage = @"PageName";
Page0 *nxtPage = [[[NSClassFromString(movePage) alloc]initWithNibName:nil bundle:nil];
[self.navigationController:nxtPage animated:YES];

Upvotes: 0

Shubham
Shubham

Reputation: 570

use like below code snippet:

Class someClassMetaClass = NSClassFromString(Str_Page);
[self.navigationController pushViewController:(UIViewController *)someClassMetaClass animated:YES];

Upvotes: 1

chandu
chandu

Reputation: 476

You can initiate a object of any class like this.

NSString *nextPage = @"Page1";
Page1 *nextclassInstance = [[[NSClassFromString(nextPage) alloc]initWithNibName:nil bundle:nil];
[self.navigationController pushViewController:nextclassInstance animated:YES];

Upvotes: 3

Related Questions