开发者

iphone sdk: objects get lost when another viewController is pushed?

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 开发者_如何学Cpushed 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):
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜