Handle

Handle

An easy-to-use and expressive Swift library for handling notifications.

2851c490 Update readme · by Aral Balkan

Handle

Handle is an easy-to-use, expressive Swift library for handling notifications.

Installation

Carthage compatible

1. Update your Cartfile

Swift 3 (latest version)

git "git@source.ind.ie:project/handle.git" ~> 4.0

For Swift 2.3:

git "git@source.ind.ie:project/handle.git" "swift-2.3"

To stay on Swift 2.2:

git "git@source.ind.ie:project/handle.git" ~> 3.0.1

2. Add the framework to your Xcode project

Follow the instructions on Carthage’s readme.

Getting started

Run the ./dev script and play with the iOS and macOS demo apps.

The Handle demonstration apps do not have any dependencies, just open up the Handle.xcworkspace in Xcode and build and run the iOS and macOS demos.

Usage

Idiom: notification enums

To provide compile-time safety and literate code, we use a notification enum idiom to define our notification names:

import Handle

public enum MyNotification:String
{
  case AwesomeNotification

  public static func named(_ notification: MyNotification) -> String
  {
    return notification.rawValue
  }
}

Post a notification

post(MyNotification.named(.AwesomeNotification), from: self)

(There are also forms that take just a notification name and allow the passing of a userInfo dictionary.)

Handle notifications

It’s easy to safely create and destroy notification handlers:

import Handle

var notificationHandler:NotificationHandler?

// Safely create a notification handler.
notificationHandler = notificationHandler ?? handle(MyNotification.named(.AwesomeNotification))
{
  /* with */ notification in

  // Do something awesome.
}

// Destroy the handler when it is no longer needed.
destroyNotificationHandler(&notificationHandler)

For handlers that should be active while a view is active, the idiom is to create the handlers on the relevant ViewController’s viewWillAppear() and to destroy them on viewWillDisappear(). The check for nil, above, guarantees that we don’t accidentally set up duplicate handlers.

Other forms

The micro-library includes NSNotificationCenter extensions as well as a form that uses selector-based event handling instead of blocks. For more information on those, please see the source code.

Read more about the library in this blog post on Ind.ie Labs.

On performance

Note that Handle is optimised for ease of authoring, beauty of interface, and clarity of intent. I haven’t run into performance issues and hence haven’t felt the need to run any benchmarks at the moment but if you want maximum performance, using the NSNotificationCenter methods directly will give you shorter stack traces.

Credits

Copyright © Aral Balkan. Released with ♥ by Ind.ie under the MIT License.