Type CCC doesnt conform to protocol 'NSObjectProtocol'

微笑、不失礼 提交于 2019-11-30 00:40:25

问题


I don't understand why my code doesn't work. Here it is:

class Test: NSURLSessionDataDelegate {

    func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {

        if(error == nil) {
            print("Hallo")
        } else {
            print(error?.userInfo)
        }
    }

    func createRequest() {

        let dictionary = [
            "mailAddress":"foo@example.com",
            .....
        ]

        let nsData: NSData?
        do {
            nsData = try NSJSONSerialization.dataWithJSONObject(dictionary, options: NSJSONWritingOptions(rawValue:0))
        } catch _ {
            nsData = nil
        }

        let defaultConfigObject = NSURLSessionConfiguration.defaultSessionConfiguration()
        let defaultSession = NSURLSession(configuration: defaultConfigObject, delegate: self, delegateQueue: NSOperationQueue.mainQueue())
        let url = NSURL(string: "http:...")!
        let urlRequest = NSMutableURLRequest(URL: url)
        urlRequest.HTTPMethod = "POST"
        urlRequest.HTTPBody = nsData
        urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
        let dataTask = defaultSession.dataTaskWithRequest(urlRequest)
        dataTask.resume()

    }
}

And the error:

Type Test does not conform to protocol 'NSObjectProtocol'.

Any ideas?


回答1:


If you follow up the inheritance chain, NSURLSessionDataDelegate inherits NSURLSessionTaskDelegate, which inherits NSURLSessionDelegate, which inherits, NSObjectProtocol. This protocol has various required methods like isEqual(_:) and respondsToSelector(_:) which you class does not implement.

Generally what you would do here is make your class inherit NSObject which conforms to NSObjectProtocol:

class Test: NSObject, NSURLSessionDataDelegate {
    ...
}



回答2:


I tried to make my class conform to protocol FBSDKSharingDelegate and got the same error. When I tried to make my subclass with superclass UIView conform to the protocol, the error went away.




回答3:


I got this error when I mistyped NSObject as NSOBject, because if you mistype it, then it isn't technically conforming to NSObject. Hope that helps someone.



来源:https://stackoverflow.com/questions/34638065/type-ccc-doesnt-conform-to-protocol-nsobjectprotocol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!