22

我有一个 Objective-C 协议,主要由 Objective-C 对象和一两个 Swift 对象使用。

我想在 Swift 中扩展协议并添加 2 个函数。一个用于注册通知,另一个用于处理通知。

如果我添加这些

func registerForPresetLoadedNotification() {
    NSNotificationCenter.defaultCenter().addObserver(self as AnyObject,
                                                     selector: #selector(presetLoaded(_:)),
                                                     name: kPresetLoadedNotificationName,
                                                     object: nil)
}

func presetLoaded(notification: NSNotification) {
    
}

我在#selector 上收到一个错误,上面写着:

'#selector' 的参数是指不暴露给 Objective-C 的方法

@objc如果我在收到错误消息时标记 presetLoaded :

@objc 只能与类的成员、@objc 协议和类的具体扩展一起使用

我也无法将协议扩展标记为@objc

当我将 Objective-C 协议创建为 Swift 协议时,我得到了同样的错误。

有没有一种方法可以适用于使用该协议的 Objective-C 和 Swift 类?

4

2 回答 2

8

实际上,您不能真正将协议扩展的功能标记为@objc(或dynamic,顺便说一句等效)。Objective-C 运行时只允许分派一个类的方法。

在您的特定情况下,如果您真的想通过协议扩展来实现,我可以提出以下解决方案(假设您的原始协议名为ObjcProtocol)。

让我们为我们的通知处理程序制作一个包装器:

final class InternalNotificationHandler {
    private let source: ObjcProtocol

    init(source: ObjcProtocol) {
        // We require source object in case we need access some properties etc.
        self.source = source
    }

    @objc func presetLoaded(notification: NSNotification) {
        // Your notification logic here
    }
}

现在我们需要扩展我们的ObjcProtocol来引入所需的逻辑

import Foundation
import ObjectiveC

internal var NotificationAssociatedObjectHandle: UInt8 = 0

extension ObjcProtocol {
    // This stored variable represent a "singleton" concept
    // But since protocol extension can only have stored properties we save it via Objective-C runtime
    private var notificationHandler: InternalNotificationHandler {
        // Try to an get associated instance of our handler
        guard let associatedObj = objc_getAssociatedObject(self, &NotificationAssociatedObjectHandle)
            as? InternalNotificationHandler else {
            // If we do not have any associated create and store it
            let newAssociatedObj = InternalNotificationHandler(source: self)
            objc_setAssociatedObject(self,
                                     &NotificationAssociatedObjectHandle,
                                     newAssociatedObj,
                                     objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            return newAssociatedObj
        }

        return associatedObj
    }

    func registerForPresetLoadedNotification() {
        NSNotificationCenter.defaultCenter().addObserver(self,
                                                         selector: #selector(notificationHandler.presetLoaded(_:)),
                                                         name: kPresetLoadedNotificationName,
                                                         object: self)
    }

    func unregisterForPresetLoadedNotification() {
        // Clear notification observer and associated objects
        NSNotificationCenter.defaultCenter().removeObserver(self,
                                                            name: kPresetLoadedNotificationName,
                                                            object: self)
        objc_removeAssociatedObjects(self)
    }
}

我知道这可能看起来不那么优雅,所以我真的会考虑改变一种核心方法。

注意事项:您可能确实想限制您的协议扩展

extension ObjcProtocol where Self: SomeProtocolOrClass
于 2016-08-16T21:08:19.500 回答
6

我找到了一种方法:) 一起避免@objc :D

//Adjusts UITableView content height when keyboard show/hide
public protocol KeyboardObservable: NSObjectProtocol {
    func registerForKeyboardEvents()
    func unregisterForKeyboardEvents()
}

extension KeyboardObservable where Self: UITableView {

    public func registerForKeyboardEvents() {
        let defaultCenter = NotificationCenter.default

        var tokenShow: NSObjectProtocol!
        tokenShow = defaultCenter.addObserver(forName: .UIKeyboardDidShow, object: nil, queue: nil) { [weak self] (notification) in
            guard self != nil else {
                defaultCenter.removeObserver(tokenShow)
                return
            }
            self!.keyboardWilShow(notification as NSNotification)
        }

        var tokenHide: NSObjectProtocol!
        tokenHide = defaultCenter.addObserver(forName: .UIKeyboardWillHide, object: nil, queue: nil) { [weak self] (notification) in
            guard self != nil else {
                defaultCenter.removeObserver(tokenHide)
                return
            }
            self!.keyboardWilHide(notification as NSNotification)
        }
    }

    private func keyboardDidShow(_ notification: Notification) {
        let rect = ((notification as NSNotification).userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
        let height = rect.height
        var insets = UIEdgeInsetsMake(0, 0, height, 0)
        insets.top = contentInset.top
        contentInset = insets
        scrollIndicatorInsets = insets
    }

    private func keyboardWillHide(_ notification: Notification) {
        var insets = UIEdgeInsetsMake(0, 0, 0, 0)
        insets.top = contentInset.top
        UIView.animate(withDuration: 0.3) { 
            self.contentInset = insets
            self.scrollIndicatorInsets = insets
        }
    }

    public func unregisterForKeyboardEvents() {
        NotificationCenter.default.removeObserver(self)
    }

}

例子

class CreateStudentTableView: UITableView, KeyboardObservable {

  init(frame: CGRect, style: UITableViewStyle) {
    super.init(frame: frame, style: style)
    registerForKeyboardEvents()
  }

  required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
}
于 2018-01-29T11:36:10.013 回答