Objective-C:调试器中的实例变量超出范围

Rón*_*áin 5 inheritance cocoa pointers scope objective-c

我有一个超类和一个子类,它们都定义了实例变量.

超类的粗略轮廓:

/* GenericClass.h */
@interface GenericClass : NSObject {
    /* some variables */
}
@end
/* GenericClass.m */
@implementation GenericClass
    /* ... */
@end
Run Code Online (Sandbox Code Playgroud)

子类概要:

/* SpecificClass.h */
#import "GenericClass.h"
@interface SpecificClass : GenericClass {
    NSMutableString *str;
}
/* SpecificClass.m */
#import "SpecificClass.h"
@implementation SpecificClass
- (void)aMethod {
    //Debugger reports str as out of scope
    str = [[NSMutableString alloc] initWithCapacity:100];
    //Works fine:
    self->str = [[NSMutableString alloc] initWithCapacity:100];
    //Doesn't compile as I haven't defined @property/@synthesize:
    self.str = [[NSMutableString alloc] initWithCapacity:100];
}
Run Code Online (Sandbox Code Playgroud)

当我使用直接从NSObject继承的类时,不需要self->指针.请注意,在父GenericClass中没有定义名称为str的对象.所以,我的问题是,为什么在未被引用为self-> str时str超出范围?代码本身可以工作,但我无法使用调试器读取变量

Ale*_*lex 7

GDB不是Objective-C编译器.编译器知道Objective-C方法中的词法范围,但GDB没有.但是,它确实了解局部变量.

在Objective-C中,每个方法self在调用时都会传递一个隐式参数.因此,当您查看时self->str,GDB正在解释它将解释任何其他本地变量评估.

当你尝试自己进行评估str时,GDB将寻找一个名为的局部变量str,而不是找到一个,报告它不在范围内.这不是错误; 这是预期的行为.