user2098707
user2098707

Reputation: 11

Accessing viewController properties from the app delegate

I am quite new to iOS programming so please be nice :) I am trying to google out this for hours now with no success. I have setup an iOS master detail project.

What i need to do. is to change a label in the detailViewController when the app calls applicationDidEnterBackground

This is my faulty code in the appdelegate applicationDidEnterBackground method

UIViewController *temp = [self.navigationController visibleViewController];
NSLog(@"%@",[temp nibName]);
if ([temp nibName] == @"DetailViewController") {
    temp._lblBrewingTime = @"";
}

This doesnt work. semantic issue: lblbrewingtime not found on object of type UIViewController. If I add a breakpoint and check the structure of the temp pointer. I can see the _lblBrewingTime type.

Can you please point me how to get the properties of whatever view is currently loaded in the app delegate?

thank you very much, Greets, Nick

Upvotes: 0

Views: 329

Answers (2)

Tarun
Tarun

Reputation: 152

You have to explicitly cast it to DetailViewController, once you are sure that the visibleViewController is DetailViewController actually. So here's the fix:-

UIViewController *temp = [self.navigationController visibleViewController];
NSLog(@"%@",[temp nibName]);
if ([temp nibName] == @"DetailViewController") {
DetailViewController* tempDVCObj = (DetailViewController*)temp;
//temp._lblBrewingTime = @"";
tempDVCObj._lblBrewingTime = @"";
}

And it says absolutely correct that your property _lblBrewingTime is not the property of UIViewController, it's the property of DetailViewController i.e. a subclass of UIViewController.

Upvotes: 2

TheEye
TheEye

Reputation: 9346

Some things here:

  1. You should keep a reference to your main controller in the AppDelegate and access the view through this reference - the visible view controller in the navigation controller may not be your view controller class, e.g. because you navigated to another view.

  2. You access the view controller via the UIViewController interface. The UIViewController class does not know about your child view controller's properties, so it cannot access the _lblBrewingType. You have to use your view controller's class name to access its properties, e.g. MyViewController * myVc = (MyViewController*)viewController.

  3. _lblBrewingType looks like an internal variable of your view controller. To access it from the outside, you must provide it as a property:

// MyViewController.h

@interface MyViewController : UIViewController

{

UILabel* _lblBrewingType;

}

@property (strong, nonatomic) IBOutlet UILabel *lblBrewingType;

And the implementation:

// MyViewController.m

@implementation MyViewController

@synthesize lblBrewingType;

@end

Upvotes: 0

Related Questions