Nat*_*han 0 operator-overloading objective-c
我刚开始用Objective-C编程,据我所知它只是部分支持方法重载,因为方法名称的生成方式(参见这个问题).
但是,我的问题是为什么我从未在任何例子中看到过它.下面的代码似乎工作正常,但我见过的任何一种例子,第二个init都会被命名initWithServerName或类似的东西,而不是利用重载.
-(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;
}
Run Code Online (Sandbox Code Playgroud)
这是什么原因?它是否会导致子类中的问题以这种方式命名方法?
与C#等Algol风格的语言不同,Objective-C的语法专为有文化的方法名称而设计.init:没有告诉我方法参数.接收器是否正在启动我正在传递的东西?不.它以某种方式使用参数,因此我们使用描述性名称initWithFormat:来指定参数是格式字符串.
而且,Objective-C根本没有方法重载.期.给定类的单个选择器只能有一个类型签名.基于参数类更改行为的唯一方法是让方法采用可包含许多不同类(如id或NSObject*)的泛型类型,请求参数为其类,并根据该查询的结果执行不同的操作.