开发者

Method Overloading in Objective-C - not used for init?

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?


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜