Setting property value of parent viewcontroller class from child viewcontroller?

时光总嘲笑我的痴心妄想 提交于 2019-12-28 18:49:09

问题


Does anyone know how to update a property value from the subview (child) view controller? I have a int property called statusid defined with gettor/settor in parent view controller. [self.view addSubview:detailsVC.view];

In the child subview, I trying calling [super statusid:updatedValue]; to update statusid to a new value, but this creates an error. How can i update statusid in the parent? Anyone know how to do this?


回答1:


with "super" you access your base class, the one your current class has inherited from

to do what you've explained, you need to access a property of your parent view, which is rather complicated since this will most likely end with both classes trying to reference each other. thus you will most likely have to create a delegate pattern, looking somewhat like this

ParentView.h

@protocol IAmYourFatherAndMotherProtocol

@class ChildView;

@interface ParentView : UIViewController <IAmYourFatherAndMotherProtocol>
{
NSInteger statusID;
}

@property (nonatomic) NSInteger statusID;

@protocol IAmYourFatherAndMotherProtocol
@property (nonatomic) NSInteger statusID;
@end

@end

in ChildView.h

#import "ParentView.h"

@interface ChildView : UIViewController
{
  id<IAmYourFatherAndMotherProtocol> delegate;
}

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

when creating your ChildView in ParentView.m, you have to set "self" as delegate, eg:

ChildView *newChild = [[ChildView alloc] init];
newChild.delegate = self;

by doing so, you can access "statusID" of your ParentView in ChildView.m like this:

delegate.statusID = 1337;

hope this helps




回答2:


Calling a method on super calls the superclass's implementation of a method, it does call the superview's/super view controller's implementation.

You either need to keep a reference to the parent from the child view controller and call the setStatusId: method on the parent, or create a delegate pattern between the two that will let the child's delegate (likely set to the parent) know that the status ID changed.



来源:https://stackoverflow.com/questions/1368757/setting-property-value-of-parent-viewcontroller-class-from-child-viewcontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!