mojuba
mojuba

Reputation: 12227

What is wrong with writing MyClass.alloc and MyClass.class in Objective C?

The compiler seems to be happy, I'm happy with slightly improved readability, but Xcode's code completion doesn't particularly recognize alloc and class when invoked this way:

MyClass* object = [MyClass.alloc initWithBounty:bounty];
<...>
if ([object isKindOfClass:MyClass.class])
    <...>

So I was wondering what is wrong with the above, if at all?

Upvotes: 0

Views: 79

Answers (2)

Chuck
Chuck

Reputation: 237080

Well, primarily what's wrong is that dot notation is for retrieving things that are conceptually properties. alloc does not access a property of the class; it creates an object. Using it for any zero-argument method is not more readable — it's confusing.

MyClass.class is actually not problematic in that way, but there's no way to declare properties on a class and they usually aren't thought of as having properties, so the autocomplete apparently doesn't support it.

Upvotes: 3

eonil
eonil

Reputation: 86065

Dot notation is originally added to be used for property access. So you can use them only for

  • A method takes no parameter and returns single value (getter).
  • A method takes single parameter and returns no value (setter).

Otherwise, recent compiler will complain about it.

Anyway, I agree to @nhgrif that using dot notation on non-property method is not a good practice.

Upvotes: 1

Related Questions