1

How can NSObject contain an NSString if NSString is an NSObject

/* NSObject.h
Copyright (c) 1994-2012, Apple Inc. All rights reserved.
*/

(NSString *)description;

NSObject has a property named 'description' that is an NSString but isn't NSString an NSObject? How is it that this works?

2
  • The same thing exists in .net
    – Andy
    Mar 14 '14 at 22:13
  • If any of the answers have answered your question don't forget to upvote them and mark top answer the one that solved it. If none of them have then add a comment to the answer to ask further details. Questions shouldn't be left open like this as then they serve no purpose Apr 4 '14 at 8:19
2

Not totally sure I understand the issue but i'll try explain. Please comment if i'm way off the mark.

Yes NSObject has an NSString as a property.

Yes NSString is a subclass of NSObject.

There is no issue in doing this. It is somewhat common, under certain circumstances, for a class to have a variable of its own type. Think of singletons for example. These are classes which hold a static copy of themselves to ensure only one can be created.

The difference here is that, NSObject has an NSString so that all its subclasses will. Every object has a description property and its a useful debugging tool, among other things. When printing an object to the console, it will call the description property and pass that as the string value, much like toString() in other languages.

You might possibly be concerned with the fact that, this means NSString has an NSString property. This is true, but calling the NSString's description will simply return the string data. Any attempt to recursively call description will result in the same value being returned.

This is all perfectly valid in the rules of inheritance.

1

A box can have another box in it. A linked list node often refers to another list node, for example, to make a list. The box inside it may be empty (null). Slightly breaking the comparison, in code, the box inside can specify itself as the box inside it as well (a this reference in Java). So it really isn't an issue. It would only be an issue if each object had a different, non-null string, since that would be infinite.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.