【问题标题】:Run method from ViewController A on ViewController B从 ViewController A 在 ViewController B 上运行方法
【发布时间】:2016-04-14 08:10:13
【问题描述】:

我有两个 ViewController:A 和 B。当用户对 ViewController A 进行更改时,我想对 ViewController B 进行一些更改。

现在我正在这样做:对于这个更改,我在 ViewController B 中有特殊的 func,并且在 ViewController B 的 viewWillApear 方法中,每次打开 ViewController 时都会运行这个 func。

也许我可以更轻松地执行它?

var GlobalVarB = 0

class ViewControllerB: UIViewController {
var localVarB = 0

func update() {
     if(localVarB != GlobalVarB) {
               localVarB = GlobalVarB
     //do something }
}

override func viewWillAppear() {
    update()
}
}

【问题讨论】:

  • 您可以创建属性并存储该属性的值。并使用它 viewC B 您也可以在 userdefault 中保存数据
  • 你的意思是 - 在 ViewController B 中创建属性?这就是我现在正在做的 - 也许我没有正确解释它。我想我可以在 ViewController B 之外运行这个方法。
  • 你可以使用协议
  • 你能解释一下吗?比我目前使用的方法容易吗?
  • 你用的是什么方法?请提供您的代码。

标签: ios objective-c swift uiviewcontroller


【解决方案1】:

你可以使用 NSNotification:

在视图控制器 B 中添加这个

- (void) viewDidLoad
{

//Your rest of code then below statement

      [[NSNotificationCenter defaultCenter] addObserver:self
            selector:@selector(receiveTestNotification:) 
            name:@"TestNotification"
            object:nil];
}

- (void) dealloc
{
     // If you don't remove yourself as an observer, the Notification Center
    // will continue to try and send notification objects to the deallocated
    // object.
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

在视图控制器 A 中

 - (void) youMethodToFireNotification
    {
         // All instances observing the `TestNotification` will be notified
        [[NSNotificationCenter defaultCenter] 
            postNotificationName:@"TestNotification" 
            object:self];   //Object here can be any changed value or you can access viewController A instance by sending self.
    }

【讨论】:

  • 虽然通知中心有其有效的用例,但在这类问题中它几乎总是错误的选择。
  • @Eiko:虽然这取决于使用什么的偏好,因为苹果不建议我们不应该为此目的使用 NSNotification。谢谢你的建议,你可以把你的答案加起来,方便我们理解。
【解决方案2】:

您可以使用 NotificationCenter 从 ViewController A 执行 ViewController B 中的方法。

在 View Controller B 中创建一个方法以根据 VC A 中的更改进行更改,并在 ViewController B viewDidLoad/ViewWillAppear 中为此通知中心添加观察者,如下所示。

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(methodName) name:@"notificationName" object:nil];

当您在视图控制器 A 中进行如下更改时,从视图控制器 A 调用发布通知。

[[NSNotificationCenter defaultCenter]postNotificationName:@"notificationName" object:nil];

您还可以使用 UserInfo 作为字典传递一些值。

希望对你有帮助。

【讨论】:

  • 虽然通知中心有其有效的用例,但在这类问题中它几乎总是错误的选择。
  • 那么这个问题的有效选项是什么?
  • 只是连接视图控制器。设置一个属性,调用它的方法。也许通过层次结构中更高的其他实例传递它。通知适用于不适合直接发送消息的极少数情况。一个非常失败的耦合,其中一个组件大喊“哦,顺便说一句,发生了这件事”,而其他一些组件可能会也可能不会听。如果您将它用于普通消息传递,则某些内容已严重损坏。
猜你喜欢
  • 2021-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多