Empty method name, what does this actually do?

ios, objective-c

Solution

The method signature `- (NSString *):name` breaks down to the following:

- `-` It is an instance method (versus a class method with a `+`).

- `(NSString *)` It returns a string.

- `:` If you were to speak the name of this method, it would simply be called "colon". `:` tells the compiler that your method accepts one parameter as well.

- `name` There is a parameter called name.

When you don't specify a type, the compiler assumes you meant `id`, so this method actually fleshes out to be `- (NSString *):(id)hello`

A valid call to this method would be: `[self :@"hello"]`.

You can do really weird things because `:` is a valid name for a method, and the compiler assumes `id`. You could, if you really wanted to, have a method called `- :::`. The compiler would assume you meant `- (id):(id):(id):(id)`, a method that returns an object of type `id` and takes three parameters of type `id`. You'd call it like so: `[self :@"hello" :anObject :myObject];`

Problem

I'm currently learning myself objective-c and iOS programming and found myself stuck with non-working code due to this subtle error for an hour. Consider the following code: ``` @property (strong, nonatomic) NSString *name; - (NSString *):name { return @"Some name"; } ``` At first glance (and for anyone new) this looks like an overridden getter for the `name` property. But theres a very subtle : that shouldn't be there. You get no warning/error from the compiler/parser/runtime here, so my question is what does this actually end up as? I tried to figure a way of calling this method once I saw the error, but didn't succeed in my few attempts.

Original source