Chuyển đến nội dung

Bài 37 · Projects and Practice

Project: An Observer and Notification Center

Build your own notification center in Objective-C with weak observers, blocks and thread safety, learn how NSNotificationCenter works, and run the same event bus design as a C stand-in.

Many parts of an app need to react to something that happened elsewhere: a download finished, the user logged out, the network changed. Passing a delegate through six layers is clumsy. The observer pattern decouples the sender from its listeners, and Cocoa ships it as NSNotificationCenter. In this project you build a small version, EventBus, to see how it works and which memory-management rules it must follow: weak references to observers, block copying, and safe removal.

Objective-C does not run on this site, so the Objective-C source is read-only. The C stand-in shows the same data structure with registered handlers, removal tokens and a payload.

Using the real thing first

OBJECTIVEC
// Observe
id token = [[NSNotificationCenter defaultCenter]
    addObserverForName:@"BankDidTransfer"
                object:nil
                 queue:[NSOperationQueue mainQueue]
            usingBlock:^(NSNotification *note) {
    NSLog(@"transfer of %@", note.userInfo[@"amount"]);
}];

// Post
[[NSNotificationCenter defaultCenter] postNotificationName:@"BankDidTransfer"
                                                    object:bank
                                                  userInfo:@{ @"amount": @40 }];

// Remove
[[NSNotificationCenter defaultCenter] removeObserver:token];

A notification has a name, an optional sender object, and an optional userInfo dictionary. The center keeps a table from names to observers. Posting is synchronous: every observer's block runs before postNotification... returns, on the posting thread unless you pass a queue.

Design of EventBus

Requirements:

  1. Observers subscribe to an event name with a block and get back a token.
  2. Posting an event calls every handler for that name with a payload dictionary.
  3. Removing a token stops delivery. Removing during delivery must not crash.
  4. Observers that go away are not kept alive by the bus, so a target object is held weakly.
  5. The bus is safe to use from several threads.
OBJECTIVEC
// EventBus.h
typedef void (^EventHandler)(NSDictionary *payload);

@interface EventToken : NSObject @end     // opaque handle, like the object returned by addObserverForName:

@interface EventBus : NSObject
+ (instancetype)shared;
- (EventToken *)subscribeToEvent:(NSString *)name
                          target:(nullable id)target           // optional, held weakly
                         handler:(EventHandler)handler;
- (void)unsubscribe:(EventToken *)token;
- (void)postEvent:(NSString *)name payload:(nullable NSDictionary *)payload;
@end
OBJECTIVEC
// EventBus.m
@interface EventToken ()
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) EventHandler handler;        // copy: the block must outlive the caller's scope
@property (nonatomic, weak) id target;                   // weak: the bus never extends the target's life
@property (nonatomic) BOOL hadTarget;
@end
@implementation EventToken @end

@interface EventBus ()
@property (nonatomic, strong) NSMutableDictionary<NSString *, NSMutableArray<EventToken *> *> *table;
@property (nonatomic, strong) dispatch_queue_t queue;
@end

@implementation EventBus

+ (instancetype)shared {
    static EventBus *bus;
    static dispatch_once_t once;
    dispatch_once(&once, ^{ bus = [[EventBus alloc] init]; });
    return bus;
}

- (instancetype)init {
    if ((self = [super init])) {
        _table = [NSMutableDictionary dictionary];
        _queue = dispatch_queue_create("com.example.eventbus", DISPATCH_QUEUE_SERIAL);
    }
    return self;
}

- (EventToken *)subscribeToEvent:(NSString *)name target:(id)target handler:(EventHandler)handler {
    EventToken *token = [[EventToken alloc] init];
    token.name = name; token.handler = handler; token.target = target; token.hadTarget = (target != nil);
    dispatch_sync(self.queue, ^{
        NSMutableArray *list = self.table[name];
        if (!list) { list = [NSMutableArray array]; self.table[name] = list; }
        [list addObject:token];
    });
    return token;
}

- (void)unsubscribe:(EventToken *)token {
    dispatch_sync(self.queue, ^{ [self.table[token.name] removeObject:token]; });
}

- (void)postEvent:(NSString *)name payload:(NSDictionary *)payload {
    __block NSArray<EventToken *> *snapshot;
    dispatch_sync(self.queue, ^{
        // copy first: handlers may subscribe/unsubscribe while we deliver
        snapshot = [self.table[name] copy];
        // drop tokens whose target has been deallocated
        [self.table[name] filterUsingPredicate:
            [NSPredicate predicateWithBlock:^BOOL(EventToken *t, NSDictionary *b) {
                return !t.hadTarget || t.target != nil;
            }]];
    });
    for (EventToken *token in snapshot) {
        if (token.hadTarget && token.target == nil) continue;
        token.handler(payload ?: @{});
    }
}
@end

Why each piece is there:

  • The copy property attribute keeps the handler block alive on the heap. See Blocks.
  • The weak target means a view controller that registers itself can be deallocated without unsubscribing, and the bus ignores it. A handler block that captures self strongly would defeat this, which is why handlers should use the weak-strong pattern.
  • Delivering from a snapshot copy of the list prevents the "mutation during enumeration" exception if a handler unsubscribes itself.
  • Handlers run outside the bus's lock. If they ran inside a dispatch_sync on the same queue and posted a nested event, the bus would deadlock.

Using it

OBJECTIVEC
__weak typeof(self) weakSelf = self;
EventToken *token = [[EventBus shared] subscribeToEvent:@"BankDidTransfer"
                                                 target:self
                                                handler:^(NSDictionary *payload) {
    typeof(self) strongSelf = weakSelf;
    [strongSelf.statusLabel setText:[NSString stringWithFormat:@"Moved %@", payload[@"amount"]]];
}];

[[EventBus shared] postEvent:@"BankDidTransfer" payload:@{ @"amount": @40 }];
[[EventBus shared] unsubscribe:token];

The same bus in C

The program below builds the structure with function pointers: subscribe returns a token (an index), post delivers to a snapshot, a handler unsubscribes itself while being delivered, and a subscriber whose "target" is gone is skipped.

C Stand-in: an event bus with tokens and safe removal

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.

The loop uses the subscription count at the start of delivery, so subscriptions added mid-delivery wait for the next event, similar to the snapshot in the Objective-C version.

Extensions to try

  • Add a priority so important observers run first.
  • Add a queue: argument that delivers on a chosen dispatch queue.
  • Support wildcard names such as Bank.*.
  • Replace the string names with typed constants and a payload class.
  • Compare the result with the real NSNotificationCenter and with KVO. Notifications broadcast by name; KVO observes one property of one object; delegates are one-to-one.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Why does the bus deliver events from a snapshot of its subscriber list?

    Mutating a collection during enumeration raises an exception; iterating a copy avoids it.
  2. 2. Why is the observer's target stored weak?

    A strong reference would prevent the observer from deallocating until it explicitly unsubscribed.
  3. 3. Why must the handler block property use copy?

    Stack blocks die with their scope; copy keeps them valid.
  4. 4. Why are handlers called outside the bus's serial-queue lock?

    dispatch_sync onto the queue you are already running on deadlocks.

Summary

  • The observer pattern decouples senders from listeners; NSNotificationCenter is Cocoa's version.
  • A correct bus copies handler blocks, holds targets weakly, delivers from a snapshot and avoids holding its lock during callbacks.
  • Observers must unsubscribe, or be held weakly, or they leak or crash.
  • Choose between notifications (broadcast), KVO (one property) and delegates (one-to-one).

Next: Practice: Questions and Exercises

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.