views:

40

answers:

3

I have just started programming in Objective-C, I understand it only partially supports method overloading due to the way the method names are generated (see this question).

However, my question is why I have never seen it used in any examples. The code below seems to work fine, but any sort of example I have seen, the second init would be named initWithServerName or something like that, instead of taking advantage of the overloading.

-(id) init {
    self = [super init];
    return self;
}

// usually this would be called initWithName or something? but to me it 
// seems easier this way because it reminds me of method overloading from C#.
-(id) init: (NSString*)newServerName {
    self = [super init];
    if(self) {      
        serverName = [[NSString alloc] initWithString:newServerName];
    }
    return self;
}

What is the reason for this? Does it cause problems in sub-classes to name methods this way?

+2  A: 

That's not the same method. In objective-C a selector named init is different than one named init:. The colon is part of the selector name.

Also, init is overridden fairly often, you just have the wrong method.

jer
+1  A: 

Aside from jer's answer, it also does not allow you to specify multiple ways to initialise an instance. For example, NSString has initWithString:, initWithFormat:, etc.

dreamlax
+4  A: 

Unlike Algol-style languages like C#, Objective-C's syntax is specifically designed for literate method names. init: tells me nothing about the method parameter. Is the receiver initing the thing I'm passing? No. It's using the argument in some way, so we use a descriptive name like initWithFormat: to specify that the argument is a format string.

Also, Objective-C does not have method overloading at all. Period. A single selector for a given class can only have one type signature. The only way to change behavior based on an argument's class is to have a method take a generic type that could include many different classes (like id or NSObject*), ask the argument for its class and do different things depending on the result of that query.

Chuck
+1 for "Objective-C does not have method overloading at all. Period."
JeremyP