在方法中使用参数会改变方法的功能吗?

发布于 2024-12-01 02:07:36 字数 573 浏览 1 评论 0原文

我尝试在谷歌和这个网站上搜索我的问题,但没有找到答案。

我是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

筱武穆 2024-12-08 02:07:36

参数是方法的输入,就像任何语言中的函数/方法参数一样。在第二个示例中,在 Frequency = newFrequency; 行上,newFrequency 应该来自哪里?

在其他语言中,您可能会遇到类似的情况

void initWithName(string newName, double newFreq);

在 Obj-C 中,等效项是

- (void)initWithName:(NSString *)newName atFrequency:(double)newFreq;

不同之处在于,在 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 is newFrequency supposed to come from?

In other languages, where you might have something like

void initWithName(string newName, double newFreq);

In Obj-C the equivalent is

- (void)initWithName:(NSString *)newName atFrequency:(double)newFreq;

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 is initWithName:atFrequency:, not just initWithName:.

(This is actually optional, you only have to have a : for each parameter. Technically initWithName:: is still a valid method name, but that's not considered good practice in Obj-C.)

See also:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文