Question

When you need to initialize a static variable in Java, you can do something like that:

public class MyClass {

  private static Object someStaticObject;
  static {
    // initialize  someStaticObject here
  }
  ...

How can you do the same in Cocoa?

Specifically, here is what I am after: I have an app with a large number of user preferences. I would like to manage all these preferences from one class where all methods are static, as follows:

@implementation Preferences

    +(void)setMotion:(BOOL)isMotion {
      [[NSUserDefaults standardUserDefaults] setBool:isMotion forKey:keyIsMotion];
      [[NSUserDefaults standardUserDefaults] synchronize];
    }

    +(BOOL)isMotion {
      [[NSUserDefaults standardUserDefaults] boolForKey:keyIsMotion];
    }

So that I can access and set my preference easily anywhere in my code with:

[Preferences setMotion:TRUE];  

or

if ([Preferences isMotion]) {
  ...

Given that I plan to have tens of static methods, it would like to have a static variable defaults defined as follows:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

so that my code above could become:

+(void)setMotion:(BOOL)isMotion {
  [defaults setBool:isMotion forKey:keyIsMotion];
  [defaults synchronize];
}

+(BOOL)isMotion {
  [defaults boolForKey:keyIsMotion];
}

However, I am not sure how to accomplish that.

Was it helpful?

Solution

In short, just declare the static variable in the implementation block of your class's implementation file (but outside of any method). Then provide accessor methods to the static variable, just as you mentioned above.

Read Class Variables for Objective-C and see also this post

OTHER TIPS

You can override + (void)initialize method on your Objective-C object.

From Apple Docs on NSObject:

The runtime sends initialize to each class in a program exactly one time just before the class, or any class that inherits from it, is sent its first message from within the program. (Thus the method may never be invoked if the class is not used.) The runtime sends the initialize message to classes in a thread-safe manner. Superclasses receive this message before their subclasses.

You can used that method it initialize static ivars and or NSUserDefaults

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top