如果我创建一个@property并对其进行合成,并创建一个getter和setter,就像这样:

#import <UIKit/UIKit.h>
{
    NSString * property;
}

@property NSString * property;

--------------------------------

@implementation

@synthesize property = _property

-(void)setProperty(NSString *) property
{
    _property = property;
}

-(NSString *)property
{
    return _property = @"something";
}


我认为这个电话正确吗

-(NSString *)returnValue
{
    return self.property; // I know that this automatically calls the built in getter function that comes with synthesizing a property, but am I correct in assuming that I have overridden the getter with my getter? Or must I explicitly call my self-defined getter?
}


这个电话是一样的吗?

-(NSString *)returnValue
{
    return property; // does this call the getter function or the instance variable?
}


这个电话是一样的吗?

-(NSString *)returnValue
{
    return _property; // is this the same as the first example above?
}

最佳答案

您的代码有很多问题,其中最重要的是您无意中定义了两个不同的实例变量:property_property

Objective-C属性语法只是普通的旧方法和实例变量的简写。您应该从没有属性的示例开始:仅使用常规实例变量和方法:

@interface MyClass {
    NSString* _myProperty;
}
- (NSString*)myProperty;
- (void)setMyProperty:(NSString*)value;

- (NSString*)someOtherMethod;
@end

@implementation MyClass

- (NSString*)myProperty {
    return [_myProperty stringByAppendingString:@" Tricky."];
}

- (void)setMyProperty:(NSString*)value {
    _myProperty = value; // Assuming ARC is enabled.
}

- (NSString*)someOtherMethod {
    return [self myProperty];
}

@end


要将此代码转换为使用属性,只需将myProperty方法声明替换为属性声明。

@interface MyClass {
    NSString* _myProperty;
}
@property (nonatomic, retain) NSString* myProperty

- (NSString*)someOtherMethod;
@end

...


实现保持不变,并且工作相同。

您可以选择在实现中合成属性,这可以删除_myProperty实例变量声明和通用属性设置器:

@interface MyClass
@property (nonatomic, retain) NSString* myProperty;
- (NSString*)someOtherMethod;
@end

@implementation MyClass
@synthesize myProperty = _myProperty; // setter and ivar are created automatically

- (NSString*)myProperty {
    return [_myProperty stringByAppendingString:@" Tricky."];
}

- (NSString*)someOtherMethod {
    return [self myProperty];
}


这些示例中的每个示例在操作方式上都是相同的,属性语法只是速记,使您可以编写更少的实际代码。

关于objective-c - @property和setters和getters,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9541828/

10-13 05:18