1

Short & sweet version of my last question in light of new information.

I have a UIVIew with an init and a drawrect method (and another thread and a bunch of other stuff, but I'll keep it short & sweet).

All of the class variables that I alloc and init in the -(id)init method are out of scope/nil/0x0 in the drawRect method, and I am unable to access them.

For example;

In the interface:

NSObject* fred;

In the implementation:

-(id)init
{
    if(self == [super init])
    {
        fred = [[NSObject alloc] init];
    }

    return self;
}

-(void)drawRect:(CGRect)rect
{
    NSLog(@"Fred is retained %i times",[fred retainCount]); //FAIL
    NSLog(@"But his variable is actually just pointing at uninitialised 0x0, so you're not reading this in the debugger because the application has crashed before it got here."
}

Should add that init IS being called before drawRect also. Anyone have any ideas?

skaffman
  • 398,947
  • 96
  • 818
  • 769
Tobster
  • 345
  • 1
  • 3
  • 12

1 Answers1

0

IS it? Have you actually put a call to NSLog in there and checked? Because I would think it's initialized with initWithFrame: or something to that effect.

Edit: Some brief testing reveals that the issue isn't that fred is uninitialized; if it was; you'd not get any error, as sending messages to nil will not cause a crash. (Instance variables are initialized to nil). What is happening, in fact, is that somewhere along the line fred is released; causing the pointer to point to garbage, rather than an object. (Or rather, a garbled or garbaged object that can no longer receive messages.)

The code you have provided is not enough to find the error; you're going to have to paste more (and the exact code used in your application, too).

Williham Totland
  • 28,471
  • 6
  • 52
  • 68
  • Unless he's calling init explicitly, which is conceivable. But initialising the variable isn't related to scope issues - scope implies that the variable isn't declared correctly. – Paul Lynch Apr 26 '10 at 10:27
  • He's confusing scope with object lifetime. Cocoa objects don't die from leaving scope. And calling `init` explicitly on an `UIView`/`NSView` subclass, is, how you say, a Bad Idea™. If fred is nil, it was never initialized; if it was created and died; fred would point at garbage. – Williham Totland Apr 26 '10 at 10:38
  • I used breakpoints to confirm execution of init, and that it is before drawRect. – Tobster Apr 26 '10 at 13:35