类不符合NSObjectProtocol [英] Class does not conform NSObjectProtocol

查看:358
本文介绍了类不符合NSObjectProtocol的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到一个错误,指出我的课程不符合NSObjectProtocol,我不知道这意味着什么。我已经从WCSessionDelegate实现了所有功能,所以这不是问题。有人知道问题出在哪里吗?谢谢!

I get an error that my class doesn't conform the NSObjectProtocol, I don't know what this means. I have implemented all the function from the WCSessionDelegate so that is not the problem. Does somebody know what the issue is? Thanks!

import Foundation
import WatchConnectivity

class BatteryLevel: WCSessionDelegate {


    var session: WCSession? {
        didSet {
            if let session = session {
                session.delegate = self
                session.activate()
            }
        }
    }

    var batteryStatus = 0.0;

    func getBatteryLevel(){
        if WCSession.isSupported() {
            // 2
            session = WCSession.default()
            // 3
            session!.sendMessage(["getBatteryLevel": ""], replyHandler: { (response) -> Void in
                if (response["batteryLevel"] as? String) != nil {
                    self.batteryStatus = (response["batteryLevel"] as? Double)! * 100
                }
            }, errorHandler: { (error) -> Void in
                // 6
                print(error)
            })
        }}


    func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
    }

    func session(_ session: WCSession, didReceiveMessage message: [String : Any]) {
    }
}


推荐答案

请参见

See Why in swift we cannot adopt a protocol without inheritance a class from NSObject?

简而言之, WCSessionDelegate 本身是从 NSObjectProtocol 继承的也可以实现该协议中的方法。实现这些方法的最简单方法是子类 NSObject

In short, WCSessionDelegate itself inherits from NSObjectProtocol therefore you need to implement methods in that protocol, too. The easiest way to implement those methods is to subclass NSObject:

class BatteryLevel: NSObject, WCSessionDelegate

请注意,您在此处处理的是Obj-C API。

Note that you are dealing with Obj-C APIs here.

这篇关于类不符合NSObjectProtocol的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆