繁体   English   中英

Objective C方法命名约定

[英]Objective C method naming convention

我目前正在使用以下约定

- (id) initWithName:(NSString *) name;

+ (NSString *) aliasForName:(NSString *) name

- (void) method

- (void) methodWithApple:(NSString *) apple andOrange:(NSString *) orange
andMango:(NSString *) mango

- (void) statusWasChanged:(id)sender

你对上述方法有更好的风格吗?

谢谢

Cocoa的编码指南是回答任何命名约定问题的重要资源。 我的答案是尽可能基于此。

Init方法

init方法看起来不错。

- (id) initWithName:(NSString *) name;

类方法

类方法看起来不错。

+ (NSString *) aliasForName:(NSString *) name

类方法也可用于实例化对象的实例。 在这个例子中,Apple的API通常使用类的名称开始,如UIButtonbuttonWithType:方法,它具有签名:

+ (id)buttonWithType:(UIButtonType)buttonType

实例方法

可以在“ 一般规则”下找到方法编码惯例的良好资源。

以下方法应该删除"and"

- (void) methodWithApple:(NSString *) apple andOrange:(NSString *) orange
andMango:(NSString *) mango  // BAD

不要使用“和”来链接作为接收者属性的关键字。

- (int)runModalForDirectory:(NSString *)path file:(NSString *) name types:(NSArray *)fileTypes;

- (int)runModalForDirectory:(NSString *)path andFile:(NSString *)name andTypes:(NSArray *)fileTypes; 错误

签名看起来应该如下所示:

- (void) methodWithApple:(NSString*)apple orange:(NSString*)orange
mango:(NSString*)mango  // GOOD

代表方法

最后,我认为可以在似乎是委托方法的方面做出一些改进:

- (void) statusWasChanged:(id)sender  // Not horrible, but not ideal

第一个改进是将类名添加到方法中。

通过标识发送消息的对象的类来启动名称:

- (BOOL)tableView:(NSTableView *)tableView shouldSelectRow:(int)row;
- (BOOL)application:(NSApplication *)sender openFile:(NSString *)filename;

第二个改进是使用"DidChange"而不是"WasChanged"

对于被调用以通知委托已发生或即将发生某些事情的方法,请使用“did”或“will”。

- (void)browserDidScroll:(NSBrowser *)sender;
- (NSUndoManager *)windowWillReturnUndoManager:(NSWindow *)window;

第三个改进是强烈转换sender参数。 我没有文档支持这一点,但示例中提供的所有示例都表明了这种行为。 请注意上面代码示例中的(NSBrowser*)sender(NSWindow*)window直接取自apple docs。

考虑到这一点,委托方法看起来应该更像:

- (void) senderClassNameStatusDidChange:(SenderClassName*)sender  // Good

如果发件人是Person对象,它看起来像:

- (void) personStatusDidChange:(Person*)sender  // Good

需要注意的是,您不应该总是在委托方法中使用“did”。

虽然您可以使用“did”或“will”来调用要求委托代表另一个对象执行某些操作的方法,但首选“should”。

- (BOOL)windowShouldClose:(id)sender;

我会说唯一一个我不确定的是:

- (void) methodWithApple:(NSString *) apple andOrange:(NSString *) orange
andMango:(NSString *) mango

看起来最后两个参数中的“和”是不必要的,或者应该用动词替换。 我认为一个好名字在很大程度上取决于调用的上下文,以及将在发送的参数中做什么。

- (id) initWithName:(NSString *) name;

任何以init开头的方法都被框架理解为返回保留对象的方法(例如, initWithObjectsAndKeysdictionaryWithObjectsAndKeys之间的区别)。 所以你应该考虑到这一点,特别是在使用ARC时。

+ (NSString *) aliasForName:(NSString *) name

使用相同的约定,这种类型的方法将返回自动释放的对象(静态方法与否)

- (void) method

我会说,如果只有一个单词,并且这个单词是名词,它应该是属性的吸气剂(如viewsuperview ......)。 否则,如果它是一个动词,为什么不添加它引用的对象? closeModalViewController一样

- (void) methodWithApple:(NSString *) apple andOrange:(NSString *) orange
andMango:(NSString *) mango

我会放弃and确实。

- (void) statusWasChanged:(id)sender

更多的Apple-y方式是statusDidChange:

除了'和'之外,这些都是很好的命名约定。 我倾向于查看Google Style Guide '。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM