[英]Objective-C setter/getter naming conventions drive me mad?
我已經嘗試理解了幾個小時,並且希望得到您的觀點。
我在一個類屬性中設置了setter / getter(我注意到我必須在setter名稱之前添加“ set”,否則編譯器會說沒有setter):
@property (nonatomic, retain, readwrite, setter=setTopString:, getter=TopString) NSString* m_topString;
當我這樣調用setter時,編譯器很高興:
[secureKeyboardController setTopString:@"This action requires that your enter your authentication code."];
但是,當我嘗試使用“點”約定時,編譯器將拒絕我:
secureKeyboardController.topString = @"This action requires that your enter your authentication code.";
真正奇怪的是,點命名約定與此屬性的配合良好:
@property (nonatomic, readwrite, getter=PINMaxLength, setter=setPINMaxLength:) NSInteger m_PINMaxLength;
在這種情況下,我可以做:
[secureKeyboardController setPINMaxLength:10];enter code here
要么
secureKeyboardController.PINMaxLength = 10;
在這兩種情況下,編譯器都很高興。
我真的很想睡得比現在少得多。 因此,將不勝感激任何解釋。
此致Apple92
您正在做的是聲明屬性,就像聲明實例變量一樣。 您不應在使用點語法的@property
聲明上使用getter
和setter
屬性中的名稱; 據我所知,它碰巧現在無法正常工作。
該屬性應與點語法一起使用。 由於某些原因-我不熟悉Cocoa編碼約定-您將屬性命名為m_topString
和m_PINMaxLength
。 這意味着您應該將它們用作someObject.m_topString
和someObject.m_PINMaxLength
。
如果要將這些名稱用於決定用於屬性后備存儲的實例變量 ,則應改為在@synthesize
指令中聲明。
這是您的類的外觀,以更符合常規的Cocoa和Objective-C編碼約定:
@interface SomeClass : NSObject {
@private
NSString *m_topString;
}
@property (nonatomic, readwrite, copy) NSString *topString;
- (id)initWithTopString:(NSString *)initialTopString;
@end
@implementation SomeClass
@synthesize topString = m_topString;
// this says to use the instance variable m_topString
// for the property topString's storage
- (id)initWithTopString:(NSString *)initialTopString {
if ((self = [super init])) {
m_topString = [initialTopString copy];
// use the ivar directly in -init, not the property
}
return self;
}
- (void)dealloc {
[m_topString release];
// use the ivar directly in -dealloc, not the property
[super dealloc];
}
- (NSString *)description {
return [NSString stringWithFormat:@"SomeClass (%@)", self.topString];
// elsewhere in your class, use the property
// this will call through its getter and setter methods
}
@end
您正在嘗試與編譯器進行對抗,然后編譯器進行了反擊。
您正在嘗試使用setter setTopString和getter TopString聲明一個名為m_topString的屬性,這顯然是愚蠢的。 您正在編寫Objective-C代碼,而不是C ++。 您的代碼將成為維護的噩夢(除非下一個維護者很明智,並將您的代碼更改為Objective-C約定)。
幫自己一個忙,開始編寫Objective-C代碼。 只需調用屬性topString,不要為setter和getter選擇您自己的名稱,不要為instance變量選擇您自己的名稱,一切就可以了。
在TopString中將T大寫,即secureKeyboardController.TopString
我確定90%可以解決您的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.