如果我创建一个@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";
}
Run Code Online (Sandbox Code Playgroud)
我是否正确地假设这个电话
-(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?
}
Run Code Online (Sandbox Code Playgroud)
这个电话是一样的吗?
-(NSString *)returnValue
{
return property; // does this call the getter function or the instance variable?
}
Run Code Online (Sandbox Code Playgroud)
这个电话是一样的吗?
-(NSString *)returnValue
{
return _property; // is this the same as the first example above?
}
Run Code Online (Sandbox Code Playgroud)
您的代码存在许多问题,尤其是您无意中定义了两个不同的实例变量: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
Run Code Online (Sandbox Code Playgroud)
要将此代码转换为使用属性,只需使用属性myProperty声明替换方法声明.
@interface MyClass {
NSString* _myProperty;
}
@property (nonatomic, retain) NSString* myProperty
- (NSString*)someOtherMethod;
@end
...
Run Code Online (Sandbox Code Playgroud)
实现保持不变,并且工作原理相同.
您可以选择在实现中合成属性,这允许您删除_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];
}
Run Code Online (Sandbox Code Playgroud)
这些示例中的每一个在操作方式上都是相同的,属性语法只是简写,允许您编写较少的实际代码.
return self.property - 将调用您被覆盖的吸气剂.
return _property; - 直接访问属性的实例变量,不调用getter.
return property; - 实例变量.
编辑:我应该强调你将有两个不同的NSString变量 - property和_property.我假设你在这里测试边界而不是提供实际的生产代码.
| 归档时间: |
|
| 查看次数: |
17593 次 |
| 最近记录: |