我有一个超类和一个子类。我可以通过子类中的some_property (在超类中声明)访问变量self.some_property。
但是,如果我尝试使用_some_property直接访问实例变量,我将得到错误'Use of undeclared identifier _some_property...'。
使用@synthesize some_property = _some_property可以消除此警告。
当我重新合成这个属性的时候发生了什么?
发布于 2016-01-09 08:27:55
您正在创建,另一个名为_some_property - and的 ivar也重写了getter方法,以返回这个新ivar的值。如果基类的@implementation (即它的_some_property ivar的隐式声明)在子类中的@synthesize站点上可见,编译器会给出一个错误。
(顺便说一句,别这样!)
您可以通过检查Obj运行时来演示:
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
@interface Base : NSObject
@property id foo;
@end
@interface Derived : Base
@end
@implementation Derived
@synthesize foo=_foo; // the compiler doesn't know about Base's _foo yet, so this is OK...
- (instancetype)init {
if ((self = [super init])) {
_foo = @"I'm derived";
}
return self;
}
@end
@implementation Base // after Derived to avoid the error
- (instancetype)init {
if ((self = [super init])) {
_foo = @"I'm base";
}
return self;
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
Derived *obj = [Derived new];
NSLog(@"getter returns %@", obj.foo);
unsigned int count = 0;
// Examine Base ivars
NSLog(@"Base ivars:");
Ivar *ivars = class_copyIvarList([Base class], &count);
for (unsigned int i = 0; i < count; i++) {
NSLog(@" %s = %@", ivar_getName(ivars[i]), object_getIvar(obj, ivars[i]));
}
// Examine Derived ivars
NSLog(@"Derived ivars:");
ivars = class_copyIvarList([Derived class], &count);
for (unsigned int i = 0; i < count; i++) {
NSLog(@" %s = %@", ivar_getName(ivars[i]), object_getIvar(obj, ivars[i]));
}
}
return 0;
}输出:
getter returns I'm derived
Base ivars:
_foo = I'm base
Derived ivars:
_foo = I'm derivedhttps://stackoverflow.com/questions/34691247
复制相似问题