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

拜拜、爱过 提交于 2020-01-06 15:18:21

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/3509467/method-overloading-in-objective-c-not-used-for-init

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!