ObjC协议的协议扩展

时间:2016-08-16 17:19:16

标签: swift protocol-extension

我有一个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上收到错误,其中显示Argument of '#selector' refers to a method that is not exposed to Objective-C

如果我将presetLoaded标记为@objc,则会收到错误消息@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes

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

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

有没有办法实现这个适用于使用该协议的Objective-C和Swift类?

2 个答案:

答案 0 :(得分:5)

实际上,您无法将协议扩展功能真正标记为 @objc (或动态,顺便说一句,这相当于)。 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

答案 1 :(得分:2)

我找到了办法:)只需避免@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")
  }
}