开发者

How to share values between two View Controller instances?

I have a View Controller that initializes a UIView as its view. That view initializes another UIView as a subview. Both UIViews communicate with the View Controller through a delegate/protocol.

Each UIView creates an instance of the ViewController and makes it equal to the delegate:

ViewController *aDelegate = [[ViewController alloc] init];
self.delegate = aDelegate;

PROBLEM: The View Controller has a variable called (int)selection that is modified by both UIViews. Both views must know how each othe开发者_如何学JAVAr modified the variable, but since each has a different instance of the View Controller that communication is impossible. How would I fix this problem?

Thanks a ton

EDIT: Peter mentioned assigning the delegate at the views creation which I like, but how would I do that for the subview since it is created in the UIView and not the View Controller. PS. In reality it is a subview of a subview of a subview so can I create them all in the View Controller and then assign it as the delegate?

Tried assigning the delegate as follows but it continually crashes when I attempt to call a ViewController method from the view:

MyView *mainView = [[MyView alloc] initWithFrame:frame];
self.view = mainView;
mainView.delegate = self;
[mainView release];


The views does not need to know about each other. In your view controller you define a property for the sub view

@property (nonatomic, retain) MyView *myView;

Then you create your sub view and assign the delegate. This can be done in viewDidLoad

- (void)viewDidLoad {
    [super viewDidLoad];

    CGRect frame = ...;
    MyView *subView = [[MyView alloc] initWithFrame:frame];
    self.myView = subView;
    subView.delegate = self;
    [self.view addSubView:subView];
    [subView release];


    self.view.delegate = self;
} 

Then in your delegate method, which I just guessed how it could look, you can update the view controller as well as the other view.

- (void)view:(MyView *)view didUpdateSelection:(int)newSelection {
    self.selection = newSelection;
    if (view == self.view) {
        self.myView.selection = newSelection;
    }
    else {
        self.view.selection = newSelection;
    }
} 


It sounds like instead of each view allocating a separate instance of the view controller, you want to assign the instance of the view controller that created the views as the delegate of each view.

One way to approach this is to have the view controller assign itself as the view's delegate when it creates the view.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜