Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 38 ยท Objects and Classes

Class Methods and Singletons

Learn class methods with the + prefix, class objects and self in class scope, the +initialize and +load hooks, class properties, and how to build a thread-safe singleton.

Some behaviour belongs to a class as a whole instead of to one instance: creating objects, returning a shared default, converting between types. Objective-C handles this with class methods, marked with + instead of -. In Objective-C a class is itself an object, which is why messages can be sent to it. This lesson covers class methods, the special +initialize and +load hooks, shared state, and the singleton pattern.

Class methods

OBJECTIVEC
@interface Temperature : NSObject
+ (double)celsiusFromFahrenheit:(double)f;
+ (instancetype)freezingPoint;
@end

@implementation Temperature
+ (double)celsiusFromFahrenheit:(double)f {
    return (f - 32.0) * 5.0 / 9.0;
}
+ (instancetype)freezingPoint {
    return [[self alloc] init];
}
@end

double c = [Temperature celsiusFromFahrenheit:212];   // 100.0

Send the message to the class name. You have used class methods already: +alloc, +stringWithFormat:, +array.

Inside a class method, self is the class object, not an instance. Therefore:

  • Use [self alloc] in factories so that subclasses return their own type.
  • You cannot use instance variables or self.property in a class method; there is no instance.
  • You can call other class methods with [self otherClassMethod].

A subclass inherits class methods and can override them, and [super ...] works there too.

Class objects

OBJECTIVEC
Class c = [Temperature class];
NSLog(@"%@", NSStringFromClass(c));          // Temperature
id instance = [[c alloc] init];              // create through a Class variable
BOOL ok = [Temperature respondsToSelector:@selector(freezingPoint)];

Passing around a Class lets you build objects chosen at run time, which is how plugin systems and NSClassFromString(@"Name") work.

Class-level state

There are no static ivars inside @interface. Use file-scope statics in the .m file, or a class property:

OBJECTIVEC
@interface Counter : NSObject
@property (class, nonatomic, readonly) NSInteger instanceCount;
@end

static NSInteger sInstanceCount = 0;

@implementation Counter
+ (NSInteger)instanceCount { return sInstanceCount; }
- (instancetype)init {
    self = [super init];
    if (self) { sInstanceCount++; }
    return self;
}
@end

Class properties do not synthesize storage; you write the accessor and keep the value in a static.

+initialize and +load

Two special class methods run automatically:

  • +initialize is called once, lazily, before the class receives its first message. Use it for light one-time setup of class-level state. It is inherited, so a subclass without its own +initialize triggers the superclass's again. Guard with if (self == [MyClass class]).
  • +load is called when the class is loaded into the process, very early, before main. Avoid it except for rare tasks such as method swizzling, because the environment is not ready.
OBJECTIVEC
+ (void)initialize {
    if (self == [Counter class]) {
        sInstanceCount = 0;
    }
}

The singleton pattern

A singleton is a class with exactly one shared instance, such as [NSApplication sharedApplication], [NSUserDefaults standardUserDefaults] or [NSFileManager defaultManager]. The standard thread-safe implementation uses dispatch_once:

OBJECTIVEC
@interface Settings : NSObject
@property (nonatomic, copy) NSString *theme;
+ (instancetype)sharedSettings;
@end

@implementation Settings

+ (instancetype)sharedSettings {
    static Settings *shared = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shared = [[self alloc] init];
    });
    return shared;
}

- (instancetype)init {
    self = [super init];
    if (self) { _theme = @"light"; }
    return self;
}
@end

dispatch_once guarantees the block runs exactly once, even if many threads call the method at the same time. After that, every call returns the same object:

OBJECTIVEC
[Settings sharedSettings].theme = @"dark";
NSLog(@"%@", [Settings sharedSettings].theme);   // dark

Mark +new and -init as NS_UNAVAILABLE in the header if you want to forbid creating other instances.

Use singletons sparingly

Singletons are global state in disguise. They make code harder to test, hide dependencies and cause ordering bugs. Prefer to pass the dependency into the objects that need it (dependency injection), and use a singleton only for truly process-wide resources such as a logger or the app delegate.

Stand-in: class-level state and a factory

The static file variable plays the part of class state. A "class method" is simply a function that takes no instance.

C Stand-in (C): class state with factory and initialize-once

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Stand-in: a singleton with run-once creation

C has pthread_once and plain statics. This version creates the shared object on first use and returns the same pointer afterwards, proving it with an address comparison.

C Stand-in (C): create once, share everywhere

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Common mistakes

  • Using self.property or ivars inside a class method.
  • Writing [ClassName alloc] in a factory so subclasses get the wrong class.
  • Doing heavy work in +load or forgetting the self == [Class class] check in +initialize.
  • Building a singleton with a plain if (!shared) check, which is not thread safe.
  • Turning everything into a singleton.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is self inside a class method?

    Classes are objects, and in a + method self is the class.
  2. 2. Which function makes a singleton thread safe?

    dispatch_once guarantees its block runs once, even under concurrent calls.
  3. 3. When is +initialize called?

    It runs lazily, once, just before the first message to the class.
  4. 4. Why prefer dependency injection over singletons?

    Passing dependencies explicitly makes code easier to test and reason about.

Summary

  • + methods belong to the class; self there is the class object.
  • Use [self alloc] in factory methods so subclasses work.
  • Class-level state lives in file-scope statics or class properties.
  • +initialize runs once lazily; avoid +load.
  • Build singletons with dispatch_once, but use them sparingly.

Next: Reference Counting and Object Ownership