Mastering macOS Programming
上QQ阅读APP看书,第一时间看更新

Understanding NSObject

Using Cocoa (and therefore Foundation) requires a certain level of familiarity with NSObject, but what exactly is this entity that seems to lie at the root of everything?

Well, in Objective C at least, NSObject was pretty much exactly that; it was the root object of most of the classes used in Objective C, and it defines many behaviors that are inherited by all of its subclasses, including those that we use in Swift.

Now, Swift itself has no explicit base object. You can declare a class, for example, like this:

class MySwiftClass 
{
var someProperty = 0
}

In the preceding code, MySwiftClass is not declared to be the subclass of any other class, and indeed, trying to make any call to super will trigger an error, since it has no superclass:

'super' members cannot be referenced in a root class
Any class declared without a superclass is considered a root class in Swift.

So what about all the functionality encapsulated in NSObject, how do we get our hands on that?

First of all, do we even need to? I think the only fair answer to that is sooner or later, almost certainly sooner, yes. There are many things you can do in Swift without using NSObject, but there are too many things that you can't. We really do need it in a number of critical situations, which we will cover as we work through the code in this book. There is no need to do this habitually; many of your classes, perhaps most of them, will never need the NSObject protocol, but some will.

Adding that NS-goodness to our classes is very easy; we simply declare our class to be a subclass of NSObject:

class MySwiftClass:NSObject 
{
var someProperty = 0
}

With this one small addition to your class declaration, your class will now slip gracefully into the Cocoa/NSObject world.