HomeiOS Developmentios - How can I migrate NotificationCenter code to Swift 6 concurrency?

ios – How can I migrate NotificationCenter code to Swift 6 concurrency?


I’m migrating a NotificationManager class to Swift 6. This class is a small utility wrapper round NotificationCenterand has a way that lets customers register a notification that can triggerunless the object is the same as a specific NSObjectworth.

For instance:

supervisor.registerObserver(for: title, forObject: nil, ignoreIfSentFrom: self) {
  // run this code _only_ if the sender wasn't self 
}

The strategy seems to be like this:

  personal func registerObserver(_ title: NSNotification.Identify, forObject object: AnyObject?,
                                ignoreIfSentFrom ignoredObject: NSObject, block: @Sendable @MainActor @escaping (Notification) -> ())
  {
    let newToken = NotificationCenter.default.addObserver(forName: title, object: object, queue: nil) { notice in
      guard (notice.object as AnyObject) !== ignoredObject else { return }
      
      Activity { @MainActor in
        block(notice)
      }
    }
    
    observerTokens.append(newToken)
  }

I get two errors right here that I can’t work out the best way to resolve:

  • Seize of 'ignoredObject' with non-Sendable sort 'NSObject?' in a '@Sendable' closure (on the guard line)
  • Sending 'notice' dangers inflicting information races; that is an error within the Swift 6 language mode (for block(notice))

Is it nonetheless potential to implement this concept with Swift 6 strict concurrency? It seems to be like Notification is neither Sendablenor @MainActor and since I don’t personal that sort, I’m at a loss for the best way to make this work.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments