开发者

Value from parentViewController

开发者 https://www.devze.com 2023-02-03 10:33 出处:网络
This class is a subclass of UITabBarViewController. In my init parent view controller file I have this:

This class is a subclass of UITabBarViewController. In my init parent view controller file I have this:

UIBarButtonItem *button1 = [[UIBarButtonItem alloc] 
                                 initWithTitle:@"Button1" 
                                 style:UIBarButtonItemStyleBordered 
                                 target:self 
                                 action:@selector(button1:)];

self.navigationItem.rightBarButtonItem = button1;

[button1 release];

And the method:

-(IBAction)button1:(id)sender {  

if (self.nvc == nil) {
    ChildViewController *vc = [[ChildViewContro开发者_如何学Goller alloc] init];   
    self.nvc = vc;
    [vc release];
}

[self presentModalViewController:self.nvc animated:YES];

I want to get an value from the parentviewcontroller in my childviewcontroller class, which also is a UITabBarViewController subclass.

How do I do this, I have tried several hours, and I only get a nil-reference.

The object I want to get(which is a property in the parent) is a NSString.

Thanks in advance


The cleanest way would probably be to create a ChildViewControllerDelegate protocol that the parent view controller implements. This is a common idiom in iOS development.

@protocol ChildViewControllerDelegate
- (NSString *)getSomeNSString;
@end

Then you should make ChildViewController have this delegate as an instance variable and be assignable via a property

@property (nonatomic, assign) id<ChildViewControllerDelegate> delegate;

Now from within ChildViewController you can use this delegate to access methods on the delegate which in your case will be ParentViewController. This will allow you to retreive the string you want.

[delegate getSomeNSString]

This may seem like a lot of work for something simple but it avoids the problems inherit with storing a back reference from ChildViewController to its parent ParentViewController.


There are a lot of ways to do this. The easiest would be to add a property to ChildViewController that points to your parent view controller. You could call it delegate. Then the method will look like:

-(IBAction)newbuilding:(id)sender {
    if (self.nvc == nil) {
        ChildViewController *vc = [[ChildViewController alloc] init];   
        vc.delegate = self;
        self.nvc = vc;
        [vc release];
    }
    [self presentModalViewController:self.nvc animated:YES];
}

Then from the ChildViewController instance you can access self.delegate.someProperty.

There are also ways to get the parent view controller without your own explicit reference (typically self.tabBarController, self.navigationController depending on context), but the above method is fool-proof, understandable and easy to debug.

0

精彩评论

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