gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 03:51:03 24 4
gpt4 key购买 nike

我有一个父类(super class)和一个子类,它们都定义了实例变量。

父类(super class)的大致轮廓:

/* GenericClass.h */
@interface GenericClass : NSObject {
/* some variables */
}
@end
/* GenericClass.m */
@implementation GenericClass
/* ... */
@end

子类大纲:

/* 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];
}

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

最佳答案

GDB 不是 Objective-C 编译器。编译器知道 Objective-C 方法中的词法作用域,但 GDB 不知道。但是,它确实理解局部变量。

在 Objective-C 中,每个方法在被调用时都有一个隐式的 self 参数传递给它。因此,当您查看 self->str 时,GDB 会对其进行解释,就像它会解释任何其他局部变量求值一样。

当您尝试单独评估 str 时,GDB 将查找名为 str 的局部变量,如果找不到,则报告它不在范围内。这不是错误;这是预期的行为。

关于Objective-C:实例变量超出调试器的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1566086/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com