简体   繁体   中英

Call method of one class to another class in ios

Actually i have created a Button in cell that access one method from another class.

#import "Cell.h"
#import "Collection.h"

@implementation Cell


-(IBAction)onClick
{
    Collection *obj_Collection = [[Collection alloc] init];
 [obj_collection goTonavigation];

}

and The method of goTonavogation is created in Collection.

#import "Cell.h"
    #import "Collection.h"
#import "NavigationViewController.h"

    @implementation Cell

-(void)goToNavigation
{
    NavigationViewController *obj_NavigationViewController = [[NavigationViewController alloc] initWithNibName:@"NavigationViewController" bundle:nil];
    [self.navigationController pushViewController:obj_NavigationViewController animated:YES];
}
}

But it's not working. please help

Your problem is instances, because you're not using existing instances, you're always creating new instances that aren't properly connected together.

I'm imagining that you have a collection view controller which is displaying cells. That is class Collection and the cells are class Cell .

Your intention is to have the cells call back to the collection view controller which is displaying them. But, your code is instead creating a new collection view controller.

Collection *obj_Collection = [[Collection alloc] init];

This new instance isn't connected to anything, doesn't have a view loaded and is part of no navigation stack. So, when you call self.navigationController you get 'nil' back.

What you should be doing is passing the cell a block for it to execute when the button is pressed, or a delegate that it can call. The delegate would be the collection view controller instance that originally created and configured the cell. The block would be created and passed when the cell is configured

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM