Objective-C setter/getter命名约定让我发疯?

use*_*607 0 getter setter objective-c

我一直试图了解几个小时的事情,我想得到你的观点.

我在我的一个类属性上有setter/getter(我注意到我必须在setter名称前添加"set",否则编译器会说没有setter):

@property (nonatomic, retain, readwrite, setter=setTopString:, getter=TopString) NSString* m_topString;
Run Code Online (Sandbox Code Playgroud)

当我像这样调用setter时,编译器很高兴:

[secureKeyboardController setTopString:@"This action requires that your enter your authentication code."];
Run Code Online (Sandbox Code Playgroud)

但是当我尝试使用"点"约定时,我被编译器拒绝了:

                secureKeyboardController.topString = @"This action requires that your enter your authentication code.";
Run Code Online (Sandbox Code Playgroud)

真正奇怪的是点命名约定适用于此属性:

@property (nonatomic, readwrite, getter=PINMaxLength, setter=setPINMaxLength:) NSInteger m_PINMaxLength;
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我可以做:

[secureKeyboardController setPINMaxLength:10];enter code here
Run Code Online (Sandbox Code Playgroud)

要么

secureKeyboardController.PINMaxLength = 10;
Run Code Online (Sandbox Code Playgroud)

在这两种情况下,编译器都很高兴.

我真的想睡得比我现在感觉的那么愚蠢.因此,我们将非常感谢任何解释.

此致,Apple92

Chr*_*son 15

您正在做的是声明属性,就像声明实例变量一样.您应该使用点语法在声明的gettersetter属性中使用名称@property; 现在恰好工作的是 - 据我所知 - 不是设计.

属性应该是您使用点语法的属性.出于某种原因 - 我不熟悉Cocoa编码约定,我希望 - 你命名你的属性m_topStringm_PINMaxLength.这意味着你应该将它们用作someObject.m_topStringsomeObject.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
Run Code Online (Sandbox Code Playgroud)