问题
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?
回答1:
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
回答2:
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
}
Hope this helps!
来源:https://stackoverflow.com/questions/6695958/bool-being-reset-to-no-in-init-method