Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we have to do [MyClass class] in Objective-C?

Tags:

objective-c

In Objective-C, you can invoke class methods with:

[MyClass aClassMethod]; 

And you can query an instance's kind with:

[someInstance isKindOfClass:[MyClass class]]; 

But, why do we need to do [MyClass class], and not simply provide MyClass like this:

[someInstance isKindOfClass:MyClass]; 

Is there a reason that the compiler is fine with encountering MyClass as a receiver (a pointer type) but not as an argument? Is it a limitation of parsing the language? Or perhaps a limitation of the compiler?

like image 398
dreamlax Avatar asked Jun 24 '10 04:06

dreamlax


People also ask

What is MyClass?

It's a service for teachers to set up their own interactive class web sites. Easy to Use -- no technical skills required. You are up and running in minutes. Powerful -- discussion boards, class announcements, homework assignments, MyClass email, and more.

What does @class do in Objective C?

@class is used for creating forward declaration of any class. If you're creating any class that's implementation is unknown to you then you can do this using @class compiler directive. You can implement this class when the implementation is known to you.

What is super in Objective C?

Super is self , but when used in a message expression, it means "look for an implementation starting with the superclass's method table."


1 Answers

Ooooh... fun question. The answer is a c-ism.

Consider:

@interface MyClass : NSObject @end @implementation MyClass @end 

Now, say you have:

... MyClass *m = nil; ... 

In that context, the compiler sees MyClass as a type definition. The * says that the variable m is a pointer to a hunk o' memory that contains one (or many -- don't forget your C pointer-fu) MyClass instances.

In other words, MyClass is a type.

But, in the context of something like:

[someInstance isKindOfClass: x ]; 

x must be an rvalue or, in human terms, the value of an expression. A type, however, cannot be used as an rvalue.

That [MyClass class] works is actually a bit of a hack, both in the language and the compiler in that the grammar specifically allows a type name to be the message receiver (to be the target of a method call).

And, as a matter of fact, you can do:

typedef MyClass Foo; .... [MyClass class]; [Foo Class]; 

It'll all work. However, you can't do the following but the error message is illuminating:

[NSUInteger class]; 

error: ‘NSUInteger’ is not an Objective-C class name or alias


Now, why not special case it everywhere as a bare name?

That colludes type names and rvalues and you quickly end up having to swallow something like [foo isKindOfClass: (MyClass)]; while barfing on [foo isKindOfClass: (MyClass *)]; which then encroaches upon typecasting territory in a rather uncomfortable fashion.

like image 134
bbum Avatar answered Oct 04 '22 21:10

bbum