flashdisk
flashdisk

Reputation: 3820

how to get access to view controller from another one?

how to get a reference to some view controller in my app?, I do not need a new copy of the view controller I just need a reference to that controller so I can use its methods and update its properties.

thanks

Upvotes: 0

Views: 107

Answers (4)

unspokenblabber
unspokenblabber

Reputation: 1557

If you are using a UINavigationController, you can do this to get the View Controller at any index

UIViewController *targetViewController = [self.navigationController.viewControllers objectAtIndex:([self.navigationController.viewControllers count]-1)];

Upvotes: 0

Clay Bridges
Clay Bridges

Reputation: 11890

Is there a parent-child relationship between the two?

If so, you might do something like

@interface ChildVC : UIViewController

@property (nonatomic, assign) ParentVC *parent;

@end

and in the ParentVC:

- (void)methodThatShowsOrCreatesChildVC
{
    // ...
    ChildVC *childVC = [[ChildVC alloc] init];
    childVC.parent = self;
    // ...
}

In the ChildVC:

- (void)methodThatChangesSomethingOnParent
{
    [[self parent] changeSomethingOnParent:something];
}

If there is not a parent-child relationship, this sounds like unnecessary coupling. Rather than that, you could try:

  • post a NSNotification about changes made
  • have a shared NSObject-based class that contains the shared "concerns".

Upvotes: 1

JuJoDi
JuJoDi

Reputation: 14975

When you push a new view controller with

performSegueWithIdentifier:

you'll get the delegate method

prepareForSegue:

Which passes a UIStoryBoardSegue that has properties destinationViewController and sourceViewController

and from this answer:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"segueName"])
    {
        YourViewController *vc = [segue destinationViewController];

        // Pass any objects to the view controller here, like...
        [vc setMyObjectHere:object];
    }
}

Upvotes: 0

zaheer
zaheer

Reputation: 893

It depends on your implementation, if the viewController is visible or is in the memory, you can access it in an other class, by creating a property and then accessing its attributes (properties, methods).

Upvotes: 0

Related Questions