开发者

Obj-c, If I'm using getters and setters for a selection screen pushed into navigation, where do I get my value back, viewWillAppear?

I'm using getters and setters on a selection screen, which is pushed onto the navigation stack, by a button on my navigation bar.

The selection screen sets the 开发者_如何学JAVAvariables, however I'm not sure where to get the value on my parent screen.

The selection screen is only initiated and defined in my navigation bar button.

Do I have to declare the viewController in my interface of my parent screen ?


There are MANY ways to do this, and over the time I've been working on iPhone software I've experimented with most of them. Here's one.

In your child view controller, you can make a property that is a pointer to the parent view controller. Thusly:

ChildViewController.h

#import "ParentViewController.h"

@interface ChildViewController : UIViewController
{
    ParentViewController *parentViewController;
}

@property (nonatomic, retain) ParentViewController *parentViewController;

ChildViewController.m

@implementation ChildViewController

@synthesize parentViewController;

-(void)dealloc
{
    [parentViewController release];
}

When you do the work to instantiate the child and push it onto the nav controller, you can set any variables you want on that child's properties, including setting, say:

ChildViewController *child = [[ChildViewController alloc] initWithNib:@"nibName" withBundle:nil];
child.parentViewController = self;
[self.navigationController pushViewController:child animated:YES];
[child release];

Then inside the child, you can talk about properties of the parent directly, as they get set by the user in the fields of the child, so...

self.parentViewController.dataField = @"My data for an NSString property of the parent view controller!";

Then when you pop the child back off, you'll find that you actually set that data into the .dataField property of the parent view controller.

(All code in this answer was typed right in here and is intended as an example only--I make no promises about spelling, syntax, etc. )


The UINavigationController gives you access to the navigation stack, check the documentation here. You can there find your parent view in the navigation history and then it should be easy to access its properties.

To find it, the UINavigationController has a method as described above:

viewControllers

The view controllers currently on the navigation stack. @property(nonatomic, copy) NSArray *viewControllers Discussion

The root view controller is at index 0 in the array, the back view controller is at index > n-2, and the top controller is at index n-1, where n is the number of items in the array.

In short: your parent view controller is at n-2.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜