在方法中使用参数会改变方法的功能吗?
我尝试在谷歌和这个网站上搜索我的问题,但没有找到答案。
我是 Obj-C 的初学者,希望回答这个问题。
在我的方法中使用参数有什么好处?
例如..
-(id)initWithName:(NSString *)newName atFrequency:(double)newFreq {
self = [super init];
if (self != nil) {
name = newName;
frequency = newFrequency;
}
return self;
}
与
-(void)myMethod {
self = [super init];
if (self != nil) {
name = newName;
frequency = newFrequency;
}
return self;
}
我理解 -(void) 意味着该方法没有返回类型,而 -(id) 意味着第一个方法具有“id”作为返回类型,而“id”是通用的... ?
谁能帮忙解释一下吗 我希望我的问题是有道理的,谢谢大家的帮助。
I've tried searching google and this site regarding my question but found no answer.
I'm a beginner with Obj-C and would like this question answered.
What is the benefit of using parameters in my methods.
for example..
-(id)initWithName:(NSString *)newName atFrequency:(double)newFreq {
self = [super init];
if (self != nil) {
name = newName;
frequency = newFrequency;
}
return self;
}
versus
-(void)myMethod {
self = [super init];
if (self != nil) {
name = newName;
frequency = newFrequency;
}
return self;
}
I understand that the -(void) means the method has no return type, and the -(id) means that the first method has 'id' as a return type, and 'id' is generic....
can anyone help explain? I hope my question makes sense, thank you all for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
参数是方法的输入,就像任何语言中的函数/方法参数一样。在第二个示例中,在
Frequency = newFrequency;
行上,newFrequency
应该来自哪里?在其他语言中,您可能会遇到类似的情况
在 Obj-C 中,等效项是
不同之处在于,在 Obj-C 中,每个参数都有一个额外的方法名称(例如
atFrequency
) — 在本例中,方法名称为initWithName:atFrequency:
,而不仅仅是initWithName:
。(这实际上是可选的,每个参数只需要有一个
:
。从技术上讲,initWithName::
仍然是一个有效的方法名称,但这在 Obj 中不被认为是好的做法-C.)另请参阅:
Parameters are inputs to a method, just like function/method parameters in any language. In your second example, on the line
frequency = newFrequency;
, where isnewFrequency
supposed to come from?In other languages, where you might have something like
In Obj-C the equivalent is
The difference is that in Obj-C, there is an extra piece of the method name for each parameter (like the
atFrequency
) — in this case, the method name isinitWithName:atFrequency:
, not justinitWithName:
.(This is actually optional, you only have to have a
:
for each parameter. TechnicallyinitWithName::
is still a valid method name, but that's not considered good practice in Obj-C.)See also: