TExcelTAD
Home › Objective-C › Design Patterns

Design Patterns

Cocoa's APIs are built around a handful of recurring patterns. You've already met delegation and target–action. This lesson covers the other three you'll see every day: the singleton, notifications with NSNotificationCenter, and Key-Value Observing, plus a word on MVC.

Singleton

A singleton is a class with exactly one shared instance, reached through a class method such as sharedInstance. Apple's own examples: [NSFileManager defaultManager], [NSNotificationCenter defaultCenter], [NSUserDefaults standardUserDefaults], [UIApplication sharedApplication].

The standard Apple implementation uses Grand Central Dispatch's dispatch_once, which guarantees the block runs exactly once, even when several threads call it at the same time:

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

GCD isn't available in this course's verifier, so the runnable version uses @synchronized, which takes a lock on an object. It behaves the same, just a little slower:

objc · try it yourself
#import <Foundation/Foundation.h>

@interface AppSettings : NSObject
@property (nonatomic, copy) NSString *theme;
@property (nonatomic) NSInteger fontSize;
+ (instancetype)sharedSettings;
@end

@implementation AppSettings
+ (instancetype)sharedSettings {
    static AppSettings *shared = nil;      // static: lives for the whole program
    @synchronized (self) {
        if (shared == nil) {
            shared = [[self alloc] init];
            NSLog(@"(creating the shared settings)");
        }
    }
    return shared;
}
- (instancetype)init {
    self = [super init];
    if (self) {
        _theme = @"light";
        _fontSize = 14;
    }
    return self;
}
@end

void changeTheme(void) {
    [AppSettings sharedSettings].theme = @"dark";
}

int main(void) {
    @autoreleasepool {
        AppSettings *a = [AppSettings sharedSettings];
        AppSettings *b = [AppSettings sharedSettings];
        NSLog(@"same object? %d", a == b);

        changeTheme();                       // some other part of the app
        NSLog(@"theme seen through a: %@", a.theme);
    }
    return 0;
}
(creating the shared settings)
same object? 1
theme seen through a: dark

Tip: Singletons are global state in disguise. They're convenient for truly app-wide services, but they make testing harder; passing objects in (dependency injection) is often the better design.

Notifications

NSNotificationCenter is a broadcast system: an object posts a named notification, and every object that registered as an observer for that name is told. The poster doesn't know who's listening, which keeps parts of an app decoupled.

objc · try it yourself
#import <Foundation/Foundation.h>

static NSString * const CartDidChangeNotification = @"CartDidChangeNotification";

@interface Cart : NSObject
@property (nonatomic, readonly) NSInteger itemCount;
- (void)addItem:(NSString *)name;
@end
@implementation Cart
- (void)addItem:(NSString *)name {
    _itemCount++;
    [[NSNotificationCenter defaultCenter] postNotificationName:CartDidChangeNotification
                                                        object:self
                                                      userInfo:@{@"added": name}];
}
@end

@interface BadgeView : NSObject
@end
@implementation BadgeView
- (instancetype)init {
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(cartChanged:)
                                                     name:CartDidChangeNotification
                                                   object:nil];
    }
    return self;
}
- (void)cartChanged:(NSNotification *)note {
    Cart *cart = note.object;
    NSLog(@"[badge] %ld item(s), just added %@", (long)cart.itemCount, note.userInfo[@"added"]);
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end

int main(void) {
    @autoreleasepool {
        BadgeView *badge = [BadgeView new];
        Cart *cart = [Cart new];

        // A second, block-based observer
        id token = [[NSNotificationCenter defaultCenter]
            addObserverForName:CartDidChangeNotification object:cart queue:nil
                    usingBlock:^(NSNotification *note) {
                        NSLog(@"[analytics] logged '%@'", note.userInfo[@"added"]);
                    }];

        [cart addItem:@"headphones"];
        [cart addItem:@"cable"];

        [[NSNotificationCenter defaultCenter] removeObserver:token];
        [cart addItem:@"case"];               // only the badge hears this one
        NSLog(@"badge still alive: %d", badge != nil);
    }
    return 0;
}
[badge] 1 item(s), just added headphones
[analytics] logged 'headphones'
[badge] 2 item(s), just added cable
[analytics] logged 'cable'
[badge] 3 item(s), just added case
badge still alive: 1

Observers are called synchronously, in the order they registered, before postNotificationName: returns. Passing object:nil when registering means "from any sender"; passing an object limits it to that sender.

Delegation Notifications
listeners exactly one any number
can answer back (return values) yes no
sender knows the receiver's protocol yes no
typical use customize one object app-wide events (keyboard shown, login changed)

Key-Value Observing (KVO)

KVO lets one object watch a property of another and be told whenever it changes through its setter, with no extra code in the observed class:

objc · try it yourself
#import <Foundation/Foundation.h>

@interface Download : NSObject
@property (nonatomic) double progress;
@end
@implementation Download
@end

@interface ProgressBar : NSObject
@end
@implementation ProgressBar
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
                        change:(NSDictionary *)change context:(void *)context {
    double old = [change[NSKeyValueChangeOldKey] doubleValue];
    double now = [change[NSKeyValueChangeNewKey] doubleValue];
    NSLog(@"%@ changed %.0f%% -> %.0f%%", keyPath, old * 100, now * 100);
}
@end

int main(void) {
    @autoreleasepool {
        Download *dl = [Download new];
        ProgressBar *bar = [ProgressBar new];

        [dl addObserver:bar forKeyPath:@"progress"
                options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew
                context:NULL];
        dl.progress = 0.25;
        dl.progress = 0.8;
        [dl removeObserver:bar forKeyPath:@"progress"];
        dl.progress = 1.0;                         // no longer observed
        NSLog(@"final progress %.0f%%", dl.progress * 100);
    }
    return 0;
}
progress changed 0% -> 25%
progress changed 25% -> 80%
final progress 100%

KVO works by creating a hidden subclass at run time whose setters send the change notifications, which is only possible because of Objective-C's dynamic runtime. Always remove observers you add.

Model–View–Controller

Apple's app architecture separates models (data and rules, plain NSObject subclasses like the classes in this course), views (what's on screen: UIView, NSView) and controllers (UIViewController) that connect them. The patterns above are the glue:

Communication Pattern
view → controller (button tap) target–action
view asks controller for data / decisions delegate & data source
model → anyone interested notifications or KVO
shared services singletons

Test yourself

What does dispatch_once guarantee in a singleton?

  1. The block runs on the main thread
  2. The block runs exactly once, even with many threads
  3. The object is never freed
  4. The method is private

How many observers can receive one posted notification?

  1. Exactly one
  2. At most two
  3. Any number
  4. None until the run loop runs

What does KVO observe?

  1. Method calls
  2. Changes to a property made through KVC-compliant setters
  3. Memory allocations
  4. Exceptions