Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

If i use the following code it shows me error "Type 'HttpConnection' does not conform to protocol 'NSObjectProtocol'"

class HttpConnection : NSURLConnectionDataDelegate {         var urlConnection       : NSURLConnection?         weak var delegate       : HttpConnecting?          init(delegate:HttpConnecting){             self.delegate = delegate;         }          func startAsynRequestWithUrlString(url:NSString, withMethod:NSString){         }     } 

If i subclass HttpConnection to NSObject then it works fine. So my question is when i need to adopt NSURLConnectionDataDelegate protocol in swift why i need to inherit the class from NSObject?

like image 291
Saurav Nagpal Avatar asked Jul 09 '14 09:07

Saurav Nagpal


People also ask

Why inherit from NSObject?

Benefits of subclassing NSObject These classes are actually Objective-C classes, meaning that classes inheriting from NSObject are in some sense “ Objective-C compatible”. Subclassing NSObject in Swift gets you Objective-C runtime flexibility but also Objective-C performance.

Does UIView inherit from NSObject?

Only classes that inherit from NSObject can be declared @objc w/ UIView.

What does NSObject mean?

The root class of most Objective-C class hierarchies, from which subclasses inherit a basic interface to the runtime system and the ability to behave as Objective-C objects.


1 Answers

NSURLConnectionDataDelegate itself inherits from NSURLConnectionDelegate which inherits from NSObjectProtocol.

That means that apart from implementing all the methods from NSURLConnectionDataDelegate, and NSURLConnectionDelegate, you also have to implement all the methods from NSObjectProtocol (e.g. equality, hash).

You didn't implement them, that's your mistake. If you inherit from NSObject, all that NSObjectProtocol methods are already implemented for you.

like image 107
Sulthan Avatar answered Sep 24 '22 19:09

Sulthan