Running Turtle
Running Turtle

Reputation: 12752

when and why would a class be a subclass of NSObject?

In some tutorials, I've seen:

class MyClass: NSObject {

    var a: String!
    var b: String!

    init(a: String, b: String) {
        super.init()
        self.a = a
        self.b = b
    }
}

I was under the impression that swift classes didn't need to subclass anything. Is there any reason why someone would want to subclass from NSObject ?

Upvotes: 1

Views: 219

Answers (2)

Sulthan
Sulthan

Reputation: 130102

NSObject class is not so important. What really is important is the NSObject protocol, in Swift named NSObjectProtocol.

For example, most protocols in Cocoa/CocoaTouch inherit from NSObjectProtocol. That means that if you want to use such protocols (for example, to implement delegates), you have to implement all the methods from NSObjectProtocol. That's pretty hard but NSObject class implements them all for you so the easiest solution is to inherit from NSObject class.

Upvotes: 2

YogevSitton
YogevSitton

Reputation: 10108

When you don't subclass NSObject you lose all the cool stuff Selector that comes with it: performSelector, respondsToSelector etc... Also - this way you can make sure your Swift code objects can interact with legacy Objective-C code.

Upvotes: 0

Related Questions