【问题标题】:BOOL being reset to NO in init methodBOOL 在 init 方法中被重置为 NO
【发布时间】:2011-10-05 11:23:14
【问题描述】:

我想在 UINavigationController 的栏中显示一个“正在播放”按钮。

我有一个类 (NowPlayingManager) 用于跟踪当前是否正在播放音频文件。我使用另一个类(AudioViewController)中发布的通知来指示播放状态。 AudioViewController 使用 alloc/init 创建 NowPlayingManager 的实例并释放它。在 NowPlayingManager 收到通知的目标中,我将 NowPlayingManager 的 isNowPlaying 布尔值设置为 YES。

当音频停止播放时,我发送另一个通知,将 isNowPlaying bool 设置为 NO。

但是,每次初始化类时,布尔值都会设置为 NO,这是有道理的,因为它是 NowPlayingManager 的一个新实例,并且永远不会显示“正在播放”按钮。

如何让 isNowPlaying 布尔值在我的 NowPlayingManager 的所有实例中持续存在?或者,我应该让应用委托初始化 NowPlayingManager 而不是 AudioViewController,以便只创建一个实例?

【问题讨论】:

    标签: ios boolean init nsnotifications


    【解决方案1】:

    您当然可以将 isNowPlaying 定义为类成员 + (BOOL) isNowPlaying。看 Objective-C: how to declare a static member that is visible to subclasses? 了解更多信息。

    但正如您已经说过的,只创建一个实例(即单例模式)似乎更有用。我建议 Matt Galaghers 发布有关单例和他可下载的 SynthesizeSingleton.h 的文章:

    http://cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html

    【讨论】:

    • 我选择了带通知的单身人士。我试图远离那个选择,但没有其他方法是实际的。
    • 不错的选择。我经常将它们用于管理器类、事件分散器、外观,.. 过了一段时间你不能没有它们:-)
    【解决方案2】:

    如果我理解正确,您应该使用NSUserDefaults。即使您更改课程、关闭应用程序等,它也会记住它。

    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"KeyName"];
    

    然后用这个检查布尔:

    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"KeyName"] == YES]
    
    {
    
        //Do whatever you would do when the bool is equal to YES
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-30
      • 1970-01-01
      • 2012-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多