Fez
Fez

Reputation: 23

Objective-C: I can't retrieve variable from another class's instance variable

In my WhatToEditViewController, I created an NSString property called whattoedit. When the user presses a certain button, whattoedit gets assigned to a string.

@interface WhatToEditViewController : UIViewController

@property (nonatomic, strong) NSString * whattoedit;

@end

#import "WhatToEditViewController.h"

Implementation:

@implementation WhatToEditViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)TappedMorning:(id)sender {
    self.whattoedit = @"Morning";
}

- (IBAction)TappedAfternoon:(id)sender {
    self.whattoedit = @"Afternoon";
}

- (IBAction)TappedEvening:(id)sender {
    self.whattoedit = @"Evening";
}

(I checked this part of my program works :/) Also when the user presses the button, a new view controller called SettingsTableViewController gets pushed in. What I want to do is set the title of the navigation bar of SettingsTableViewController as WhatToEditViewController's whattoedit property.

Here is SettingsTableViewController's implementation:

#import "SettingsTableViewController.h"
#import "WhatToEditViewController.h"

@interface SettingsTableViewController ()

@end

@implementation SettingsTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    WhatToEditViewController * editMode = [[WhatToEditViewController alloc] init];

    self.navigationController.navigationBar.topItem.title = editMode.whattoedit;
}

Oddly, the navigation bar title turns into (null). Should the navigationBar.title code be in the viewDidLoad?

Upvotes: 1

Views: 42

Answers (1)

Pepeng Hapon
Pepeng Hapon

Reputation: 377

It is because you're initializing new WhatToEditViewController at viewDidLoad in your SettingsTableViewController, so the value of whattoedit becomes NULL

The correct way is to create a instance variable in your SettingsTableViewController that will update the value of title:

So, when you click the button to push in SettingsTableViewController, you should update the value like this:

In your SettingsTableViewController.h:

@property (nonatomic, strong) NSString *titleValue;

In your WhatToEditViewController, when you push

- (IBAction)pushToSettingVC:(id)sender {

SettingsTableViewController *setting = [self.storyboard instantiateViewControllerWithIdentifier:@"SettingsTableViewController"];
    setting.titleValue = YOUR_NEW_TITLE_VALUE_HERE;
    [self.navigationController pushViewController:setting animated:YES];

}

and in your SettingsTableViewController.m viewDidLoad

- (void)viewDidLoad {
    [super viewDidLoad]; 
    self.title = self.titleValue
}

Upvotes: 2

Related Questions