Some code not executing in a method called from another ViewController

旧城冷巷雨未停 提交于 2019-12-24 05:55:04

问题


My problem
I have a standard UIViewController. With the press of a button, it loads a form sheet modal view controller. When dismissing this modal view with the press of a UIBarButtonItem I call a method by doing:

ViewController *main = [[ViewController alloc] initWithNibName:nil bundle:nil];
[main updateLabel];

In the method -(void)updateLabel in the main ViewController I'm setting the text of a label, but the label won't change. But I know the function gets called, because if I do a NSLog(@"Method call test); instead of label.text = @"Test" I can see the message in console.

What am I doing wrong? It must be the way I'm calling the method in the main ViewController, because I can easily change the label anywhere else.

What I want to do:
When dismissing a modal view controller, I want a method to be called in the main view controller, and in this case change the text of a label.

Thanks for your help!


回答1:


You're creating a new instance of ViewController with that code, not getting a pointer to the one you already have.

If ViewController is the controller that presented the modal view, then you can get a pointer to it with,

ViewController *main = self.presentingViewController;



回答2:


A better way to do this would be to use the delegate pattern.

https://developer.apple.com/library/ios/documentation/general/conceptual/DevPedia-CocoaCore/Delegation.html

The following is a design pattern suggestion

The modal view controller shouldn't know how to dismiss itself, that is the responsibility of the presenting view controller. After all, it could have been presented in many different ways (modally, popover, push navigation). Using the delegate pattern, the modal view controller would tell its delegate that it should be dismissed when the bar button item gets pressed. The delegate, which is the presenting view controller, would then dismiss the modal view and update the label mentioned in your question.



来源:https://stackoverflow.com/questions/22849894/some-code-not-executing-in-a-method-called-from-another-viewcontroller

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