UIView drawRect; class variables out of scope

2019-07-29 18:27发布

问题:

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?

回答1:

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).



标签: cocoa uiview