Coding Guidelines for Cocoa是回答任何命名約定問題的好資源。我的回答儘可能基於此。
初始化方法
init方法看起來不錯。
- (id) initWithName:(NSString *) name;
類方法
類方法看起來不錯。
+ (NSString *) aliasForName:(NSString *) name
類方法也可用於實例化對象的實例。在這種情況下,蘋果的API通常有類似的UIButton
buttonWithType:
方法的類名稱的方式啓動具有簽名:
+ (id)buttonWithType:(UIButtonType)buttonType
實例方法
良好的資源用於編碼規範的方法可以是根據General Rules找到。
下面的方法應該放棄的"and"
S:
- (void) methodWithApple:(NSString *) apple andOrange:(NSString *) orange
andMango:(NSString *) mango // BAD
不要使用「and」來連接兩個表示接受者屬性的關鍵字。
- (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文檔中獲取。
考慮到這一點,委託方法應該看起來更像是:
- (void) senderClassNameStatusDidChange:(SenderClassName*)sender // Good
如果發件人是一個Person對象它看起來像:
- (void) personStatusDidChange:(Person*)sender // Good
一個忠告就是你不應該總是在委託方法中使用「did」。
雖然可以用「沒有」或「會」爲所調用的方法 要求委託做代表其他物體的東西,「應該」 是首選。
- (BOOL)windowShouldClose:(id)sender;
對於'initWithName'確保您瞭解ARC將如何對待這個(即返回保留的對象) – Thilo
你的命名約定好.. –