Objective-C中的方法重载-不用于init吗? [英] Method Overloading in Objective-C - not used for init?

查看:87
本文介绍了Objective-C中的方法重载-不用于init吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始使用Objective-C进行编程,我了解由于方法名称的生成方式,它仅部分支持方法重载(请参见

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).

但是,我的问题是为什么我从未在任何示例中看到它.下面的代码似乎可以正常工作,但是我看到的任何示例,第二个init都将被命名为initWithServerName或类似的名称,而不是利用重载.

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?

推荐答案

与C#等Algol风格的语言不同,Objective-C的语法是专门为有素方法名设计的. init:告诉我关于方法参数的任何信息.接收者在初始化我要传递的东西吗?否.它以某种方式使用了参数,因此我们使用诸如initWithFormat:之类的描述性名称来指定参数为格式字符串.

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.

此外,Objective-C根本没有方法重载.时期.给定类的单个选择器只能具有一个类型签名.更改基于参数类的行为的唯一方法是让方法采用通用类型,该类型可以包含许多不同的类(例如idNSObject*),向参数询问其类并根据参数进行不同的操作该查询的结果.

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.

这篇关于Objective-C中的方法重载-不用于init吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆