这个问题在这里已经有了答案:
类型CCC不符合协议'NSObjectProtocol'2的 答案我得到一个错误,我的类不符合NSObjectProtocol,我不知道这是什么意思。 我已经实现了WCSessionDelegate的所有功能,所以这不是问题。 有人知道问题是什么吗? 谢谢!
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]) { } }This question already has an answer here:
Type CCC doesnt conform to protocol 'NSObjectProtocol' 2 answersI 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]) { } }最满意答案
看看为什么在swift中我们不能没有从NSObject类继承协议?
简而言之, WCSessionDelegate本身从NSObjectProtocol继承,因此您也需要在该协议中实现方法。 实现这些方法的最简单方法是子类NSObject :
class BatteryLevel: NSObject, WCSessionDelegate请注意,您正在处理Obj-C API。
See Why in swift we cannot adopt a protocol without inheritance a class from 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, WCSessionDelegateNote that you are dealing with Obj-C APIs here.
更多推荐
发布评论