gpt4 book ai didi

objective-c - @property 以及 setter 和 getter

转载 作者:行者123 更新时间:2023-12-03 06:15:20 26 4
gpt4 key购买 nike

如果我创建一个 @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 实例变量声明和通用属性 setter :

@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 以及 setter 和 getter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9541828/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com