如何在没有协议的情况下在两个View Controller之间传递值?

the*_*ect 0 cocoa-touch objective-c ios

我有两个视图控制器,打电话给他们viewA,并ViewB

  • 所有动作都发生在主视图中 - ViewA
  • 菜单按钮被点击,显示ViewB,一切都很好,菜单出现

现在,用户触摸一个IBAction按钮,以编程方式只需要:

  1. 改变的价值BOOL,它调用myBOOLYES
  2. 解雇 ViewB
  3. myBOOL变量的当前状态传递YESViewA

我已经声明了相同的BOOL,set属性,在两个视图上合成,但是根据我NSLog的解雇ViewB和加载ViewA,它恢复到NO

所以我知道我正在切线,我只是想知道你是否可以发送BOOL两个控制器之间的值,如果是这样,请给我一个例子......因为搜索找到了Protocols和Delegate示例NSString' s,当我尝试使用时,BOOL我会陷入导入循环,但是我已经读过它可能会创建一个全局的BOOL,就像它一样糟糕的设计,我现在只需要克服这个块.

Maz*_*yod 7

关于这个主题的问题应该更多地关注NSNotificationCenter而不是NSUserDefaults注意两者都是单身.

NSUserDefaults:

这个类的目的不是在类之间传递变量.它的目的是存储用户的默认值.(即偏好,设置等).

NSNotificationCenter:

这个类非常方便,并且有许多不同的用途,其中之一是为任何类接收广播变量.接收类称为观察者.这种模式称为观察者模式.

注意:NSUserDefaults方法的优点是允许您在初始化其他类之前设置变量,并且可以随时检索.然而,这真的很草率(恕我直言)并被认为是不好的做法.


快速和脏代码示例NSNotificationCenter:

// upon initializing the class that wants to observe the changes, we add it as an observer.
// So, somewhere in the A.m, upon being initialized (init, maybe?).

- (id)init {
    if (self = [super init]) {
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(calledUponNotif:)
                                                     name:@"MyObserveKey"
                                                   object:nil];
    }
    return self;
}

// the selector should look something like this:
- (void)calledUponNotif:(NSNotification *)notif {
    id sentVar = [notif object];
}
Run Code Online (Sandbox Code Playgroud)
// Somewhere in the B.m
    [[NSNotificationCenter defaultCenter] postNotificationName:@"MyObserveKey"
                                                        object:varToSend];
Run Code Online (Sandbox Code Playgroud)

另一个注意事项:在调用postNotification方法之后,将同步调用另一个类中的已注册选择器,因此您不必担心这一点.