我应该如何设置一个可供所有app控制器使用的布尔值?

时间:2012-07-15 14:03:32

标签: ios global-variables

我的应用中有一个帮助模式,当应用处于帮助模式时,“告诉”所有按钮的行为方式不同。

我希望设置一个全局布尔值,指示应用程序是否处于帮助模式。

最佳做法是什么?

由于 沙尼

2 个答案:

答案 0 :(得分:1)

我建议将它放在App Delegate中,然后通过以下方式访问它:

AppDelegate *myAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
myAppDelegate.yourboolean = YES;

继续这样做。或使用NSNotification。当您的应用进入帮助模式时,在视图控制器中设置启用帮助模式的NSNotification。

//Put this right after the switch for help mode is turned on!

    [[NSNotificationCenter defaultCenter] postNotificationName:@"helpModeOn" object:yourboolean];

并且在帮助模式影响的所有其他视图控制器或文件中应该具有:

-(void)viewDidLoad:
{
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ThingYouWantToDoWhenHelpModeIsOn:) name:@"helpModeOn" object:nil];
}

- (void)ThingYouWantToDoWhenHelpModeIsOn:(NSNotification *)notification{
        // Make sure you have an BOOL in your header file for all the other view controllers
        ThatBooleanValue = [notification object];
        [self performSelector:@selector(OtherThings:) object:ThatBooleanValue];
}

希望这有帮助!

答案 1 :(得分:0)

您可以设置全局静态布尔值,并通过某个.h文件将其作为extern使用。在某些情况下,这是完全可以接受的方式。

如果您希望用户以他们离开的方式返回您的应用,例如他们现在处于帮助模式,请在第二天离开并返回并仍处于帮助模式,然后我可以使用偏好设置通过NSUserDefaults进行操作。