2013-10-17 247 views
-1

我有一個具有以下屬性的類:Objective-C的命名約定方法

  • 名稱
  • 電子郵件
  • 用戶名

我想這些屬性轉換爲字典。我怎樣才能正確地說出遵循蘋果慣例的方法?

我在想:

- (NSDictionary *) convertToDictionary {} 
+0

什麼叫類? – Claudiu

+1

另請參閱Apple的[Cocoa編碼指南:命名方法](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingMethods.html)。 – Rob

回答

4

如何只-dictionaryRepresentation,傳達你可以得到存儲在字典的形式對象中的數據的概念?所以,你會說:

NSDictionary *personDict = [person dictionaryRepresentation]; 

另一種合理的選擇是-properties,離開返回類型出了名的:

NSDictionary *personDict = [person properties]; 
1

認爲,這從一個NSStringNSData你去:

NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding]; 

同樣,你可以只是做:

- (NSDictionary *)dictionary; 

因爲您沒有參數。或者考慮從NSDataNSString你做:

[[[NSString alloc] initWithData:data encoding:encoding] autorelease] 

類方法,如果有一個,看起來像:

[NSString stringWithData:data encoding:encoding] 

,所以你可以把它的類別上NSDictionary。假設你的類被稱爲Account

+ (NSDictionary *)dictionaryWithAccount:(Account *)account; 

取決於你想看起來更好:

Account *account = ...; 

[account dictionary]; 
[NSDictionary dictionaryWithAccount:account]; 
+0

他有一個班級和一個實例。他爲什麼要把它變成一個類方法(+ dictionaryWithAccount :)?這沒有什麼意義。 –

+0

@ChristianKienle:你是對的,編輯過。 – Claudiu