A Protocol-Oriented NotificationCenter which is type safe, thread safe and with memory safety

Overview


A Protocol-Oriented NotificationCenter which is type safe, thread safe and with memory safety.

  • Type Safe

    No more userInfo dictionary and Downcasting, just deliver the concrete type value to the observer.

  • Thread Safe

    You can register, notify, unregister in any thread without crash and data corruption.

  • Memory Safety

    SwiftNotificationCenter store the observer as a zeroing-weak reference. No crash and no need to unregister manually.

It's simple, safe, lightweight and easy to use for one-to-many communication.

Usage

Define protocol and observer:

protocol Update {
    func updateTitle(title: String)
}

extension ViewController: Update {
  func updateTitle(title: String) {
  		self.titleLabel.text = title
  }
}
let vc = ViewController()

Register:

Broadcaster.register(Update.self, observer: vc)

Broadcast:

Broadcaster.notify(Update.self) {
    $0.updateTitle("new title")
}

Unregister:

Broadcaster.unregister(Update.self, observer: self)

Compare with NSNotificationCenter :

For example, handle UIKeyboardWillShowNotification

@objc func handleKeyboardNotification(notification: NSNotification) {
    guard notification.name == NSNotification.Name.UIKeyboardWillShow
        else { return }
    
    guard let beginFrame = (notification
        .userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue
        else { return }
    
    guard let endFrame = (notification
        .userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
        else { return }
    // use beginFrame, endFrame
}

SwiftNotificationCenter way:

/*
If you want to observe the system built in notifications like this.
You can declare a protocol and the relevant method, and use a singleton as a mediator to observe system's notification, then notify our observers.
Please check the refactor example in SwiftNotificationCenterExample Project.
*/
func UIKeyboardWillShow(beginFrame: CGRect, endFrame: CGRect) {
}

Installation

CocoaPods:

pod 'SwiftNotificationCenter'

Carthage:

github "100mango/SwiftNotificationCenter"

Manually:

Just copy source files in the SwiftNotificationCenter folder into your project.

License

SwiftNotificationCenter is under the MIT license.

Comments
  • Crash with `register(_:observer:)`

    Crash with `register(_:observer:)`

    When registering for observing, app crashes with:

    fatal error: expecting reference type but found value type: ...
    

    This started happening since I updated to Xcode 8.3 & Swift 3.1

    opened by gapl 9
  • Fix for use of flatMap in Swift 4.1+

    Fix for use of flatMap in Swift 4.1+

    Hi,

    Thanks for creating SwiftNotificationCenter!

    In Swift 4.1 and beyond, using flatMap on optional values is deprecated and one should use compactMap. Since this is only used in once place, I simply added a compiler directive to use the correct method based on the Swift version.

    opened by edwardmp 2
  • Constraint the observer to be class

    Constraint the observer to be class

    '''
    public static func register(_ protocolType: T.Type, observer: T)
    ''' better constraint the T to be class, though no error reported when registering a struct.

    opened by Johnkui 1
  • fix for xcode10 debug crashes

    fix for xcode10 debug crashes

    Crash was happening due having some nil objects inside self.objects variable.

    What I did was a quick fix for having the build working with swift 4.2 and being able to ship my app back to production.

    PR's code is about removing all nil objects inside self.objects before adding new ones.

    opened by lucascarletti 0
  • Register to notifications with execution queue

    Register to notifications with execution queue

    I would like to offer you to add an execution queue parameter to register functions. It will be really useful when SwiftNotificationCenter is using for UI changing.

    opened by GrigoryUlanov 0
  • xcode10 debug crashes

    xcode10 debug crashes

    Random crashes when app run in xcode10 debug mode, always break in same place. mutating func add(_ object: T){ self.objects.formUnion([WeakObject(object)]) }

    Error is Thread 13: Fatal error: Duplicate element found in Set. Elements may have been mutated after insertion.

    Use the laster pod version.

    What can i do?

    opened by jianmu297 9
Releases(1.0.4)
Owner
null
NotificationCenter based Lightweight UI / AnyObject binder.

Continuum NotificationCenter based Lightweight UI / AnyObject binder. final class ViewController: UIViewController { @IBOutlet weak var label: UI

Taiki Suzuki 82 Apr 4, 2021
A Swift based Future/Promises Library for IOS and OS X.

FutureKit for Swift A Swift based Future/Promises Library for IOS and OS X. Note - The latest FutureKit is works 3.0 For Swift 2.x compatibility use v

null 759 Dec 2, 2022
Write great asynchronous code in Swift using futures and promises

BrightFutures How do you leverage the power of Swift to write great asynchronous code? BrightFutures is our answer. BrightFutures implements proven fu

Thomas Visser 1.9k Dec 20, 2022
The easiest Future and Promises framework in Swift. No magic. No boilerplate.

Promis The easiest Future and Promises framework in Swift. No magic. No boilerplate. Overview While starting from the Objective-C implementation of Ju

Alberto De Bortoli 111 Dec 27, 2022
Promises is a modern framework that provides a synchronization construct for Swift and Objective-C.

Promises Promises is a modern framework that provides a synchronization construct for Objective-C and Swift to facilitate writing asynchronous code. I

Google 3.7k Dec 24, 2022
Lightweight promises for iOS, macOS, tvOS, watchOS, and Linux

Futures Futures is a cross-platform framework for simplifying asynchronous programming, written in Swift. It's lightweight, fast, and easy to understa

David Ask 60 Aug 11, 2022
Futures and Promises library

#PureFutures A simple Futures and Promises library. ##Installation ###Carthage Add the following in your Cartfile: github "wiruzx/PureFutures" And ru

Victor Shamanov 17 Apr 5, 2019
A dead-simple abstraction over the iOS BackgroundTask API to make background tasks easy to isolate, maintain and schedule

A dead-simple abstraction over the iOS BackgroundTask API to make background tasks easy to isolate, maintain and schedule. Designed to be as lightweight and flexible as possible while tightly integrating with the system APIs. And It's built with Swift Concurrency in mind.

Sam Spencer 31 Dec 11, 2022
MemoryCache - type-safe, thread-safe memory cache class in Swift

MemoryCache is a memory cache class in swift. The MemoryCache class incorporates LRU policies, which ensure that a cache doesn’t

Yusuke Morishita 74 Nov 24, 2022
Protocol oriented, type safe, scalable design system foundation swift framework for iOS.

Doric: Design System Foundation Design System foundation written in Swift. Protocol oriented, type safe, scalable framework for iOS. Features Requirem

Jay 93 Dec 6, 2022
Modern thread-safe and type-safe key-value observing for Swift and Objective-C

Now Archived and Forked PMKVObserver will not be maintained in this repository going forward. Please use, create issues on, and make PRs to the fork o

Postmates Inc. 708 Jun 29, 2022
NoticeObserveKit is type-safe NotificationCenter wrapper.

NoticeObserveKit NoticeObserveKit is type-safe NotificationCenter wrapper. // .keyboardWillShow is a static property. Notice.Center.default.observe(na

Taiki Suzuki 147 Nov 24, 2022
NoticeObserveKit is type-safe NotificationCenter wrapper.

NoticeObserveKit NoticeObserveKit is type-safe NotificationCenter wrapper. // .keyboardWillShow is a static property. Notice.Center.default.observe(na

Taiki Suzuki 147 Nov 24, 2022
Implemented MVVM-C (Coordinator) architecture pattern for the project. Which is satisfying SOLID principles altogether. Protocol oriented development has been followed.

BreakingBad BreakingBad API doc Implemented MVVM-C (Coordinator) architecture pattern for the project. Which is satisfying SOLID principples altogethe

Dhruvik Rao 2 Mar 10, 2022
Type-safe networking abstraction layer that associates request type with response type.

APIKit APIKit is a type-safe networking abstraction layer that associates request type with response type. // SearchRepositoriesRequest conforms to Re

Yosuke Ishikawa 1.9k Dec 30, 2022
Type-safe thread-local storage in Swift

Threadly is a Swift µframework that allows for type-safe thread-local storage. What is Thread-Local Storage? Thread-local storage (TLS) lets you defin

Nikolai Vazquez 71 Aug 6, 2022
⚡️ Fast async task based Swift framework with focus on type safety, concurrency and multi threading

Our apps constantly do work. The faster you react to user input and produce an output, the more likely is that the user will continue to use your appl

Said Sikira 814 Oct 30, 2022
A bidirectional Vapor router with more type safety and less fuss.

vapor-routing A routing library for Vapor with a focus on type safety, composition, and URL generation. Motivation Getting started Documentation Licen

Point-Free 68 Jan 7, 2023
A bidirectional router with more type safety and less fuss.

swift-url-routing A bidirectional URL router with more type safety and less fuss. This library is built with Parsing. Motivation Getting started Docum

Point-Free 242 Jan 4, 2023
Interface-oriented router for discovering modules, and injecting dependencies with protocol in Objective-C and Swift.

ZIKRouter An interface-oriented router for managing modules and injecting dependencies with protocol. The view router can perform all navigation types

Zuik 631 Dec 26, 2022