Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class Objects and Instance Variables in Objective-C

I'm having a hard time wrapping my head around this concept. I'll take the quote exactly from the book:

Class objects also inherit from the classes above them in the hierarchy. But because they don’t have instance variables (only instances do), they inherit only methods.

Correct me if I'm wrong, but a class object would be this:

NSString *aString = [[NSString alloc]initWithString:@"abc.."];

The class object in this case is *aString -- am I correct so far?

The thing that confuses me is the second sentence in the quote above, "But because they don’t have instance variables (only instances do), they inherit only methods."

I thought that an object (in this case *aString) was the instance of the NSString class. The second sentence above is implying that an instance is something different. It's not making any sense to me.

like image 453
Andy Avatar asked Dec 27 '22 18:12

Andy


1 Answers

You are incorrect.

NSString *aString = [[NSString alloc] initWithString:@"abc..."];

In this line, we have, from left-to-right:

  • A type: NSString *
  • A variable name: aString
  • an assignment
  • A Class: NSString
  • An invocation of a class method: +alloc
  • An invocation of an instance method on the return value of the class method: -initWithString:
  • An object being passed as a parameter to the instance method: @"abc..."

In Objective-C, a Class is actually a kind of object. You can interact with them in many of the same ways that you can instances, but since they are "classes", they cannot have instance variables (since instance variables, by definition, are only for instances). Classes only have methods. They inherit from other Classes, and this is how object inheritance is implemented.

For more information on this, check out this awesome blog post by Greg Parker: http://www.sealiesoftware.com/blog/archive/2009/04/14/objc_explain_Classes_and_metaclasses.html

like image 178
Dave DeLong Avatar answered Dec 31 '22 14:12

Dave DeLong