-1

I am new to ios development and started coding with swift,and I have some basic question regarding NSOject and i couldn't find any satisfactory answer.

My question is, If we are creating a new class ,is it mandatory that the class must inherit from the root class of the foundation (i.e), NSObject or it is optional as now we have swift file template in xcode.

 import UIKit

 class Myclass: NSObject {

 }

or

import UIKit

     class Myclass {  // where here myclass is the base class

     }

Any help would be appreciated...

Mike Purcell
  • 19,847
  • 10
  • 52
  • 89
Legolas
  • 805
  • 1
  • 11
  • 24

4 Answers4

3

There are quite some differences between using and not using NSObject.

Jasper Blues has written a nice explanation what the pros and cons of using NSObject are.

Long story short:

Subclassing NSObject in Swift gets you Objective-C runtime flexibility but also Objective-C performance. Avoiding NSObject can improve performance if you don't need Objective-C's flexibility.

Community
  • 1
  • 1
Christian
  • 22,585
  • 9
  • 80
  • 106
1

You do not have to inherit from NSObject. However, you may want to inherit from NSObject if you want certain runtime features. For example if you want to use KVO (Key Value Observing), or you would like to do some more advanced things like method swizzling.

In general, I would recommend not inheriting from NSObject unless you find a problem that requires it.

Mr Beardsley
  • 3,743
  • 22
  • 28
1

The above answers are correct, but there are many instances where you may need/want to inherit from NSObject anyway. @Mr. Beardsley mentioned a couple. I would add that if you are interacting with the Cocoa/Cocoa Touch APIs, or many of Apple's other frameworks, you may want to inherit from NSObject for a number of interoperability reasons.

For example, if you want your class to conform to the NSCoding protocol, or any of the standard delegate or data source protocols (like UITableViewDataSource, for example) then you will save yourself a lot of trouble by inheriting from NSObject. I agree with the advice to not inherit unless you need it, but I find that it is often necessary when working with Apple's APIs.

Aaron Rasmussen
  • 13,082
  • 3
  • 42
  • 43
0

Optional.

From the documentation at https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Inheritance.html

Swift classes do not inherit from a universal base class. Classes you define without specifying a superclass automatically become base classes for you to build upon.

Usernumbernine
  • 276
  • 1
  • 8