我对Objective-C中的第一个参数有疑问
-(NSInteger) totalSeconds:(NSInteger)h minutes:(NSInteger)m seconds:(NSInteger)s;
我注意到,似乎第一个参数通常被“拉入”消息名称本身并且没有命名。
[totalSeconds:9 minutes:59 seconds:59]
这种语法是否可以接受:
-(NSInteger) totalSeconds:hours:(NSInteger)h
minutes:(NSInteger)m seconds:(NSInteger)s;
我环顾四周并没有看到这样的例子,尽管我预计它会很常见。
答案 0 :(得分:9)
您的特定语法将作为消息声明,但结果将不成为您的期望。
-(NSInteger) totalSeconds:hours:(NSInteger)h
minutes:(NSInteger)m seconds:(NSInteger)s;
编译器将看到的方式如下:
-(NSInteger) totalSeconds:(id)hours:
(NSInteger)h
minutes:(NSInteger)m
seconds:(NSInteger)s
hours
成为id
参数类型的参数名称,而不是h
参数的标识符。为了打电话,电话看起来非常时髦:
[self totalSeconds:nil :12 minutes:50 seconds:42];
请注意,您现在必须传递一个对象作为第一个参数(我选择了nil
),并且单词hours
不再在调用中。
我不会以这种方式命名消息。正如Rudedog在这里所说的,我的想法是你应该能够像英语句子一样阅读这个电话。使用与他或Nick Veys'类似的名称。
来自你的评论:
这是我的问题的一部分。就是它 标准方式?适应的名称 方法本身就是第一个 参数而不是标记 第一个参数就像你做其他参数一样。
是的,标准是将消息命名为第一个参数“name”是消息本身的一部分。了解选择器包含所有这些信息。如上所述,消息的选择器是:
totalSeconds::minutes:seconds
如命名更好,选择器应该读取如下内容:
totalSecondsFromHours:minutes:seconds
答案 1 :(得分:5)
我可能会说出那个方法
[totalSecondsWithHours:9 minutes:59 seconds:59]
方法命名的想法是你应该能够阅读这个电话并让它看起来像一个英文句子。
答案 2 :(得分:4)
为什么不能这样:
-(NSInteger) secondsFromHours:(NSInteger)h minutes:(NSInteger)m seconds:(NSInteger)s
答案 3 :(得分:4)
“消息名称”不仅仅是它的第一个组件,而是所有在参数之前的标记。
考虑一个名为totalSeconds
的方法。很容易,这是一个吸气剂。有道理,对吗?现在考虑一个名为totalSeconds:
的方法。这没有多大意义,因为它没有确定论证应该是什么。这就是为什么,而不是foo:
,您经常会看到fooWithBar:
,并且从该模式可以扩展fooWithBar:baz:hax:
。
在第一个示例中,方法名称为totalSeconds:minutes:seconds:
。我认为这是一个很好的建议,称之为secondsFromHours:minutes:seconds:
。
答案 4 :(得分:2)
此:
[totalSeconds:9 minutes:59 seconds:59]
不是有效的消息表达式。 Objective-C消息的语法是:
[receiver message]
您上面写的内容会尝试向-:minutes:seconds:
发送totalSeconds
条消息