我对财产重新申报有疑问
概述:
- 类“A”是具有只读属性 int n1 的父类;
- 类“B”是子类,它将属性重新声明为读写
- 使用“B”类的设置器,属性值设置为 20
- 当我使用 getter 和实例变量打印值时,我似乎得到了不同的值
注意点: - 内存管理 = ARC (Automatic Reference Counting)
问题:
- 当我打印 self.n1 和 _n1 的值时,为什么会得到不同的值?
- 为什么我的预期行为和实际行为不匹配(请向下滚动查看实际与预期)?
代码:(在单独的文件中)
啊
#import<Foundation/Foundation.h>
@interface A : NSObject
@property (readonly) int n1;
- (void) display;
@end
是
#import "A.h"
@implementation A
@synthesize n1 = _n1;
- (void) display
{
printf("_n1 = %i\n", _n1); //I expected _n1 and self.n1 to display the same value
printf("self.n1 = %i\n\n", self.n1); //but they seem to display different values
}
@end
溴化氢
#import"A.h"
@interface B : A
@property (readwrite) int n1;
@end
BM
#import"B.h"
@implementation B
@synthesize n1 = _n1;
@end
测试.m
#import"B.h"
int main()
{
system("clear");
B* b1 = [[B alloc] init];
b1.n1 = 20;
[b1 display]; //Doubt - my expected behavior is different from actual behavior
return(0);
}
预期行为:
_n1 = 20
self.n1 = 20
实际行为:
_n1 = 0
self.n1 = 20