Question

I have a UIButton in MainViewController.
MainViewController has a childViewContoller.

I need to access the UIButton (tcButton) property in MainViewController FROM the childViewController and set it to setSelected:YES in viewDidLoad. I have the following code in my ChildViewController.m file and it's not working.

#import "ChildViewController.h"
#import "MainViewController.h"
#import "CoreData.h"

@interface ChildViewContoller () 
@property (nonatomic, strong) CoreData *coreData;
@property (nonatomic, strong) MainViewController *mainViewController;
@end

@implementation ChildViewController
@synthesize coreData, mainViewController;

-(void)viewDidLoad 
{
    [super viewDidLoad];
    self.managedObjectContext = [(STAppDelegate *)[[UIApplication sharedApplication]  delegate] managedObjectContext];
    [[(mainViewController *)self.parentViewController tcButton] setSelected:YES];
}
Was it helpful?

Solution

Your code is kind of a mess. Why are you creating a new instance of yourself in viewDidLoad? This makes no sense. If ChildViewController is truly a child view controller, then you can access the parent with self.parentViewController. You only need one line in the viewDidLoad:

-(void)viewDidLoad // Line 4
{

    [[(MainViewController *)self.parentViewController tcButton] setSelected:YES]; // Line 8
}

OTHER TIPS

There are several issues in your code but the main idea to perform what you want is getting a pointer to the mainViewController. There are many ways to do that but here a simple example how you can implement such thing. For instance in the initializer of the ChildViewContoller you can pass a pointer to the mainViewController:

@interface ChildViewContoller ()

@property (nonatomic, strong) MainViewController *mainViewController;

@end

@implementation ChildViewContoller

- (id)initWithMainViewController:(MainViewController *)mainViewController
{
    self = [super init];

    if (self)
    {
        _mainViewController = mainViewController;
    }

    return self;
}

- (void)viewDidLoad
{
    [_mainViewController.tcButton setSelected:YES];
}

@end

Please not that I have not tested the code above but you can get the idea.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top