属性未在drawRect方法中设置 - iOS

dam*_*hy. 2 objective-c drawrect ios quartz-core

当我尝试访问drawRect方法中的类变量或属性时,我一直看到一些奇怪的行为.

在我的.h文件中,我有以下内容

@interface DartBoard : UIView
{
    Board * board;
    int index;
}
@property (readwrite, assign, nonatomic) NSNumber * selectedIndex;
@end
Run Code Online (Sandbox Code Playgroud)

在我的.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
Run Code Online (Sandbox Code Playgroud)

输出是

2012-06-12 19:48:42.579 App [3690:707] selectedIndex: 0
2012-06-12 19:48:42.580 App [3690:707] index: 0
Run Code Online (Sandbox Code Playgroud)

我一直试图找到一个解决方案,但没有运气..

我发现了类似的问题,但问题没有真正的答案

见:UIView drawRect; 类变量超出范围

我有一种感觉drawRect与普通方法不同,并没有正确地获得类的范围,但我该如何解决它?

干杯达米恩

Kur*_*vis 5

我有一种感觉drawRect与普通方法不同,并没有正确地获得类的范围

不,没什么特别的-drawRect:.

有两种可能性:

1.你的-init方法没有被调用.

您没有说明如何创建此视图 - 如果您是手动调用[[DartBoard alloc] init],或者是否从nib文件中取消归档.

如果它来自笔尖,那么UIViewunarchiving不知道init应该调用你的方法.它将调用指定的初始化程序,即-initWithFrame:.

所以,你应该实现该方法,并确保调用超级!

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.selectedIndex = [NSNumber numberWithInt:5];
        index = 123;
    }
    return self;
}
Run Code Online (Sandbox Code Playgroud)

2. 您的视图可能有两个实例:一个是您手动执行的init,另一个是来自其他地方的实例,可能是一个笔尖.第二个实例是正在绘制的实例.由于其变量和属性从未设置,因此它们显示为零(默认值).

您可以将此行添加到您的方法-init-drawRect:方法中,以查看其值self.(或者,使用调试器检查它.)

NSLog(@"self is %p", self);
Run Code Online (Sandbox Code Playgroud)