0

I want to show a Now Playing button in a UINavigationController's bar.

I have a class (NowPlayingManager) that I am using to keep track of whether an audio file is currently being played. I use a notification posted in another class (AudioViewController) to indicate playing status. AudioViewController creates an instance of the NowPlayingManager with alloc/init and releases it. In NowPlayingManager's target of the received notification I set NowPlayingManager's isNowPlaying Boolean to YES.

When the audio stops playing I send another notification that sets the isNowPlaying bool to NO.

However, each time the class is initialized the bool is set to NO, which makes sense because it is a new instance of NowPlayingManager and the Now Playing button is never displayed.

How can I get the isNowPlaying bool to persist through all instances of my NowPlayingManager? Or, rather, Should I have the app delegate init the NowPlayingManager rather than AudioViewController so that only one instance is created?

Michael Morrison
  • 1,323
  • 1
  • 18
  • 30

2 Answers2

0

If I understand correctly, you should use NSUserDefaults. This remembers it even if you change class, close the app, etc.

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

And then check the bool with this:

if ([[NSUserDefaults standardUserDefaults] boolForKey:@"KeyName"] == YES]

{

    //Do whatever you would do when the bool is equal to YES

}
Nimantha
  • 6,405
  • 6
  • 28
  • 69
Jack Humphries
  • 13,056
  • 14
  • 84
  • 125
0

You can of course define the isNowPlaying as class member + (BOOL) isNowPlaying. See Objective-C: how to declare a static member that is visible to subclasses? for more information on this.

But as you said already it seems to be more useful to create just one instance i.e. the singleton pattern. I suggest Matt Galaghers posting about singletons and his downloadable SynthesizeSingleton.h:

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

Community
  • 1
  • 1
Kay
  • 12,918
  • 4
  • 55
  • 77
  • I went with a singleton with notifications. I was trying to stay away from that choice but nothing else is practical. – Michael Morrison Jul 16 '11 at 02:18
  • Good choice. I use them pretty often for manager classes, event dispathers, facades,.. Ater a while you can't live without them :-) – Kay Jul 16 '11 at 08:55