Objective C方法命名约定 - 冒号的用法

时间:2014-04-05 22:51:18

标签: objective-c methods naming-conventions

我是Objective C的新手。

我正在阅读这里的教程:https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingMethods.html#//apple_ref/doc/uid/20001282-BCIGIJJF

它说:

在所有参数之前使用关键字。 正确的方法:

- (void)sendAction:(SEL)aSelector toObject:(id)anObject forAllCells:(BOOL)flag;

错误的方式:

- (void)sendAction:(SEL)aSelector :(id)anObject :(BOOL)flag;

让我对Objective-C的方法名称感到困惑。这是我的问题:

1

不推荐错误的方法。但这完全合法,对吗?

2

方法的名称(签名?)是 sendAction:toObject:forAllCells:表示第一个, sendAction ::: 表示第二个。对? 我注意到人们强调冒号:总是计算在方法名称中。 我假设:表示将跟随一个参数,无论如何都不能修改它。那么在方法名称中包含冒号的含义是什么,因为它不受我的修改。

3

举一个例子, - (void)sendAction:(SEL)aSelector;

所以方法的名称应该是sendAction:

注意冒号之前的空格是名称的一部分,我应该将其视为与 - (void)sendAction:(SEL)aSelector; 不同的方法吗?

答案应为NO [anObject sendAction:anSel];应该与[anObject sendAction:anSel];

相同

你们如何理解这个有意义的整体方案? 谢谢。

P.S。通过这个问题欣赏你的阅读。我很确定一旦你们中的一些人指出并清除了我的困惑,我会感到愚蠢。

1 个答案:

答案 0 :(得分:1)

错误的方式是合法的,是的,但风格不好。不要这样做。冒号是使ObjC代码很好阅读的一部分(虽然详细);呼叫站点上的所有参数都有标签,提醒您它们的用途以及它们应该是什么类型。

该空间实际上不是方法名称的一部分;它被忽略了。关于ObjC的其中一个问题就是"compiler-specified"

@interface Jackson : NSObject

- (void)shootCannon :(double)range;

- (void)grillSandwichWithBread :(BreadType)bread cheese :(CheeseType)cheese;

@end

@implementation Jackson
@end

int main(int argc, const char * argv[])
{

    @autoreleasepool {

        NSLog(@"%@", NSStringFromSelector(@selector(shootCannon:)));
        NSLog(@"%@", NSStringFromSelector(@selector(shootCannon :)));
        NSLog(@"%@", NSStringFromSelector(@selector(grillSandwichWithBread:cheese:)));
        NSLog(@"%@", NSStringFromSelector(@selector(grillSandwichWithBread :cheese :)));

        NSLog(@"%d", @selector(shootCannon:) == @selector(shootCannon :));
        NSLog(@"%d", @selector(grillSandwichWithBread:cheese:) == @selector(grillSandwichWithBread :cheese :));

    }
    return 0;
}
  

2014-04-05 23:59:29.548 MethodNameSpace [66948:303] shootCannon:
  2014-04-05 23:59:29.548 MethodNameSpace [66948:303] shootCannon:
  2014-04-05 23:59:29.549 MethodNameSpace [66948:303] grillSandwichWithBread:cheese:
  2014-04-05 23:59:29.550 MethodNameSpace [66948:303] grillSandwichWithBread:cheese:
  2014-04-05 23:59:29.550 MethodNameSpace [66948:303] 1
  2014-04-05 23:59:29.551 MethodNameSpace [66948:303] 1

相关问题