首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当你合成一个子类的变量时会发生什么?

当你合成一个子类的变量时会发生什么?
EN

Stack Overflow用户
提问于 2016-01-09 08:14:45
回答 1查看 73关注 0票数 3

我有一个超类和一个子类。我可以通过子类中的some_property (在超类中声明)访问变量self.some_property

但是,如果我尝试使用_some_property直接访问实例变量,我将得到错误'Use of undeclared identifier _some_property...'

使用@synthesize some_property = _some_property可以消除此警告。

当我重新合成这个属性的时候发生了什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-01-09 08:27:55

您正在创建,另一个名为_some_property - and的 ivar也重写了getter方法,以返回这个新ivar的值。如果基类的@implementation (即它的_some_property ivar的隐式声明)在子类中的@synthesize站点上可见,编译器会给出一个错误。

(顺便说一句,别这样!)

您可以通过检查Obj运行时来演示:

代码语言:javascript
复制
#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;
}

输出:

代码语言:javascript
复制
getter returns I'm derived
Base ivars:
 _foo = I'm base
Derived ivars:
 _foo = I'm derived
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34691247

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档