Kalle
Kalle

Reputation: 13346

Variable declarations inside of a method causing gdb garbage output prior to instantiation

This is a really weird one and I'm wondering if I need to change my coding style a bit or if gdb is bugging out on me.

The structure of one of my methods looks like this:

{
    // code that checks if this method needs to do something
    // ...

    // further down, I instantiate e.g. foo as an NSArray
    NSArray *foo = bar;
    // ...
}

If I debug the above code, I happen to have a NSDictionary called sizes. Because I am instantiating foo some lines into the method, I keep getting these errors in console up until foo is created:

-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x541cb90

The reason why this happens is that both sizes and foo are pointing at the same memory 0x541cb90. But since I haven't even CREATED foo yet, I can't really do anything about it. The error appears repeatedly until I step into the foo = bar point, where it stops appearing. The reason it appears is I think because it's trying to show me the values for it in the debug variable window to the right.

This may be related to libXcodeDebuggerSupport.dylib is missing in iOS 4.2.1 development SDK

Is it simply bad practice to declare variables "throughout" a method like this? It feels wasteful to declare every variable I ever intend to use inside a method at the very top, but maybe I have to...?

Upvotes: 0

Views: 123

Answers (1)

Tommy
Tommy

Reputation: 100652

I haven't seen this particular issue, but I'd tend heavily towards it being best practice to declare variables as close as possible to where they are used — exactly as you're doing.

As a sort of test of Apple's attitude, I logged in to the iOS Developer Centre and grabbed — at random — the sample code projects avTouch, GLSprite and AccelerometerGraph.

Of those, avTouch unambiguously declares variables mid-method at lines 171, 183 and 188 of avTouchController.mm. There are also a couple declared at the top of a block (in the old fashioned sense, not the GCD sense).

GLSprite contains mid-method declarations at lines 107 and 108 of EAGLView.m.

AccelerometerGraph contains similar declarations at line 257, 332 and 516 of GraphView.m, plus lots more examples of variables at the top of a block.

In none of the projects did I see a variable that appeared to have been moved to the top of a method artificially.

So I'm inclined to think that Apple agree with both you and me. This is just the Xcode graphical front-end to GDB being unhelpful.

Upvotes: 1

Related Questions