I have been seeing some strange behavior when I try to access a class variable or a property in my drawRect method..
In my .h file I have the following
@interface DartBoard : UIView
{
Board * board;
int index;
}
@property (readwrite, assign, nonatomic) NSNumber * selectedIndex;
@end
In my .m file I have the following
@implementation DartBoard
@synthesize selectedIndex;
-(id)init
{
self.selectedIndex = [NSNumber numberWithInt:5];
index = 123;
return self;
}
- (void)drawRect:(CGRect)rect {
NSLog(@"selectedIndex: %d",[self.selectedIndex intValue]);
NSLog(@"index: %d",index);
}
@end
the output is
2012-06-12 19:48:42.579 App [3690:707] selectedIndex: 0
2012-06-12 19:48:42.580 App [3690:707] index: 0
I have been trying to find a solution but have had no luck..
I found a similar question but there was no real answer to the issue
See: UIView drawRect; class variables out of scope
I have a feeling drawRect is different that normal methods and is not getting the scope of the class correctly but how do I fix it?
Cheers
Damien
No, there is nothing special about
-drawRect:.There are two possibilities:
1. Your
-initmethod is not being called.You didn’t say how this view gets created — if you are manually calling
[[DartBoard alloc] init], or if it is getting unarchived from a nib file.If it’s coming from a nib,
UIView‘s unarchiving doesn’t know that yourinitmethod should be called. It will call the designated initializer instead, which is-initWithFrame:.So, you should implement that method instead, and make sure to call super!
2. There might be two instances of your view: one that you are manually
initing, and another one that comes from somewhere else, probably a nib. The second instance is the one that is being drawn. Since its variables and properties are never set, they show up as zero (the default value).You could add this line to both your
-initand-drawRect:methods, to see what the value ofselfis. (Or, check it using the debugger.)