views:

851

answers:

1

I have a superclass and a subclass, both of which define instance variables.

Rough outline of superclass:

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

Outline of subclass:

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

When I am using classes that inherit directly from NSObject, one doesn't need the self-> pointer. Note that there is no object with the name str defined in the parent GenericClass. So, my question is, why is str out of scope when not referenced as self->str? The code in itself works, but I can't read the variable with the debugger

+5  A: 

GDB is not an Objective-C compiler. The compiler knows about things like lexical scope within Objective-C methods, but GDB does not. It does, however, understand local variables.

In Objective-C, every method has an implicit self parameter passed to it when it's called. So when you look at self->str, GDB is interpreting that like it would interpret any other local variable evaluation.

When you try to evaluate str on its own, GDB will look for a local variable called str and, not finding one, reports that it's not in scope. This is not an error; this is the expected behavior.

Alex
This is a good clarification of how the GDB works, thanks! But there is one thing still confusing me. I have variables defined in the superclass; let's call one NSMutableString *superstr. A reference to "superstr" on its own in the implementation of SpecificClass works fine. But attempting to access a variable "str" defined in SpecificClass.h doesn't work in the debugger without using self->. How does GDB find an inherited variable, but not one defined in this class's own header? If I'm not using inheritance, this also works just fine. It seems like a bug in XCode
Rónán Ó Braonáin
Try `po str` and `po superstr` in the Debugger Console window (⇧⌘R). If those give the same results, the problem has nothing to do with Xcode (which is likely).
Peter Hosey
Oddly enough, po str and po superstr work fine in the console, as do po self->str and po self->superstr. It's only in the visual debug UI where the str variable without self-> reports being out of scope when moved over with the mouse, but read/write operations in the code work just fine. I'll log it as a bug with Apple. Meanwhile I'm using self-> everywhere (although I'd prefer not to) so that I can visually debug.
Rónán Ó Braonáin