iphone - Objective C 方法命名约定

标签 iphone objective-c ios xcode

我目前正在使用以下约定

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

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

- (void) method

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

- (void) statusWasChanged:(id)sender

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

谢谢

最佳答案

Coding Guidelines for Cocoa是回答任何命名约定问题的重要资源。我的回答是尽可能基于此。

初始化方法

init 方法看起来不错。

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

类方法

类方法看起来不错。

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

类方法也可用于实例化对象的实例。在这种情况下,Apple 的 API 的方法通常以类名开头,例如 UIButton。的 buttonWithType:具有签名的方法:

+ (id)buttonWithType:(UIButtonType)buttonType

实例方法

有关方法编码约定的良好资源可以在 General Rules 下找到.

以下方法应该删除 “和”:

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

Don’t use “and” to link keywords that are attributes of the receiver.

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

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

签名应该更像下面这样:

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

Delegate Methods

最后,我认为可以对委托(delegate)方法进行一些改进:

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

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

Start the name by identifying the class of the object that’s sending the message:

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

第二个改进是使用"DidChange"代替"WasChanged"

Use “did” or “will” for methods that are invoked to notify the delegate that something has happened or is about to happen.

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

第三个改进是强投发送者参数。我没有支持这一点的文档,但是示例中提供的所有示例都表现出这种行为。请注意上面直接取自 Apple 文档的代码示例中的 (NSBrowser*)sender(NSWindow*)window

考虑到这一点,委托(delegate)方法应该更像:

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

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

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

请注意,您不应该总是在委托(delegate)方法中使用“did”。

Although you can use “did” or “will” for methods that are invoked to ask the delegate to do something on behalf of another object, “should” is preferred.

- (BOOL)windowShouldClose:(id)sender;

关于iphone - Objective C 方法命名约定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8410602/

相关文章:

iphone - 编辑 'iOS Default'(和 'Mac OS X')的build设置模板

iphone - AudioQueue 的暂停录音回调

ios - iOS 中原生 View 和混合 Web View 之间的切换

ios - 未收到随机主队列调度

objective-c - NSScreen的可见框太大

ios - VTCompressionSessionCreate 适用于 iOS 9 但不适用于 iOS 8

iphone - 如何检查 iCloud 是否以编程方式配置

ios - UIBarButtonItem选择到下一个ViewController

ios - UITableViewCells 未出现在第二个选项卡中

ios - 单行 UILabel 拥抱不适用于自动收缩