当我尝试访问drawRect方法中的类变量或属性时,我一直看到一些奇怪的行为。
在我的.h文件中,我有以下
@interface DartBoard : UIView
{
Board * board;
int index;
}
@property (readwrite, assign, nonatomic) NSNumber * selectedIndex;
@end
在我的.m文件中,我有以下
@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
输出
2012-06-12 19:48:42.579 App [3690:707] selectedIndex: 0
2012-06-12 19:48:42.580 App [3690:707] index: 0
我一直试图找到一个解决方案,但没有运气..
我发现了一个类似的问题,但问题没有真正的答案
请参阅:UIView drawRect; class variables out of scope
我有一种感觉drawRect与普通方法不同,并没有正确地获得类的范围,但我该如何解决?
干杯 达明
答案 0 :(得分:5)
我有一种感觉drawRect与普通方法不同,并没有正确地获得类的范围
不,-drawRect:
没有什么特别之处。
有两种可能性:
<强> 1。您的-init
方法未被调用。
您没有说明如何创建此视图 - 如果您手动调用[[DartBoard alloc] init]
,或者是否从nib文件中取消归档。
如果它来自笔尖,UIView
的取消存档并不知道应该调用您的init
方法。它会改为调用designated initializer,即-initWithFrame:
。
因此,您应该实现该方法,并确保调用super!
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
self.selectedIndex = [NSNumber numberWithInt:5];
index = 123;
}
return self;
}
<强> 2。您的视图可能有两个实例:您手动init
,另一个来自其他地方,可能是笔尖。第二个实例是正在绘制的实例。由于它的变量和属性从未设置,因此它们显示为零(默认值)。
您可以将此行添加到-init
和-drawRect:
方法中,以查看self
的值是多少。 (或者,使用调试器进行检查。)
NSLog(@"self is %p", self);