views:

28

answers:

1

Hi, everyone, i have no idea why this doesn't work hopefully someone here can help me out. Here's what i'm trying to do:

I've got two ViewControllers, lets call them secondViewController and firstViewController. The firstViewController is shown when the application starts and it pushes the secondViewController.

Inside the secondViewController i defined a property.

Now i want to change this property in the firstViewController and then push the secondViewController but for some reason as soon as the secondViewController is pushed my property is reseted to zero.... why is this happening? heres my code:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
 secondViewController.test = 2;
[self.navigationController pushViewController:secondViewController animated:YES];       

}

The test property in this example is just a simple NSInteger. Now as soon the secondViewController is pushed the "test" value is no longer two it's zero..... Why????

here's the header file of my secondViewController: #import

@interface secondViewController : UIViewController {

NSInteger test;

}

@property NSInteger test;

@end

here's the .m file:

- (void) viewDidLoad{
NSLog(@"%i", self.test):
}
A: 

If you're checking it from the viewDidLoad test may not always be 2. I actually don't understand why that is either. Example:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    SecondViewController viewController = [[SecondViewController alloc] init];
    viewController.test = 2;
    [self.navigationController pushViewController:viewController animated:YES];
}

// In SecondViewController

- (void)viewDidLoad {
    NSLog(@"ViewDidLoad: %i", self.test);

    [super viewDidLoad];
}

- (void)viewWillAppear:(BOOL)animated {
    NSLog(@"ViewWillAppear: %i", self.test);

    [super viewWillAppear:animated];
}

This will sometimes result in the following output:

ViewDidLoad: 0

ViewWillAppear: 2

But sometimes it may also result in the following output:

ViewDidLoad: 2

ViewWillAppear: 2

So, I recommend you to use your variable in the ViewWillAppear-method instead of the ViewDidLoad-method. You should create your UIView's and stuff in the ViewDidLoad-method and adjust them to your test-variable in the ViewWillAppear-method :).

It's a bit confusing, I know, and it took me a few hours to figure out why my variable wasn't set already too.

Tim van Elsloo
Thanks i got i working! but then i ran into another problem:I want to add a thirdViewController and the property mentioned above now belongs to this thirdViewController. i set the property in the firstViewController. THen i push the secondViewController. The secondViewController pushes the thirdViewController!As soon as i arrive at the thirdViewController my property is lost.... Any ideas?
Christoph v
i figured it out. Thanks very much!
Christoph v
You're welcome.
Tim van Elsloo