Khyati Vaishnav
Khyati Vaishnav

Reputation: 43

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

Upvotes: 0

Views: 676

Answers (1)

Wain
Wain

Reputation: 119041

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

Upvotes: 2

Related Questions