Xcode os x:为什么drawRect无法访问实例数据



我试图在自定义视图中绘制一些内容,但不确定drawRect无法访问其实例数据的原因。这是我试过的步骤。

  1. 创建一个Mac OS X应用程序,并选中使用情节提要
  2. 在情节提要中,删除该视图,然后在该视图的同一位置添加新的自定义视图。(如果视图没有被删除,我也尝试过)
  3. 将EEGView类分配给新添加的自定义视图

然后跑步。从日志信息中,您会注意到drawRect无法访问实例数据,尽管实例变量已初始化并更新。

在viewCtroller.m 中

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    myView = [[EEGView alloc] init];
    //[self.view addSubview:myView];
    //Start Timer in 3 seconds to show the result.
    NSTimer* _timerAppStart = [NSTimer scheduledTimerWithTimeInterval:2
                                                      target:self
                                                    selector:@selector(UpdateEEGData)
                                                    userInfo:nil
                                                     repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_timerAppStart forMode:NSDefaultRunLoopMode];
    }
    - (void)UpdateEEGData
{
    //    NSLog(@"UpdateEEGData.....1");
    //    myView.aaa = 200;
    //    myView.nnn = [NSNumber numberWithInteger:myView.aaa];
    // make sure this runs on the main thread
    if (![NSThread isMainThread]) {
        // NSLog(@"NOT in Main thread!");
        [self performSelectorOnMainThread:@selector(updateDisplay) withObject:nil waitUntilDone:TRUE];
    }else
    {
        [self.view setNeedsDisplay:YES];
    }
    NSLog(@"UpdateEEGData.....2");
    [myView setAaa:400];
    myView.nnn = [NSNumber numberWithInteger:myView.aaa];

    // make sure this runs on the main thread
    if (![NSThread isMainThread]) {
        // NSLog(@"NOT in Main thread!");
        [self performSelectorOnMainThread:@selector(updateDisplay) withObject:nil waitUntilDone:TRUE];
    }else
    {
        [self.view setNeedsDisplay:YES];
    }
}
    -(void)updateDisplay
{
    [self.view setNeedsDisplay:YES];
}

在我的自定义视图类EEGView.m 中

@implementation EEGView
@synthesize aaa;
@synthesize nnn;
-(id)init{
    self = [super init];
    if (self) {
        aaa = 10;
        nnn = [NSNumber numberWithInteger:aaa];
        NSLog(@"init aaa: %i", aaa);
        NSLog(@"init nnn: %i", [nnn intValue]);
    }
    return self;
}
    - (void)drawRect:(NSRect)dirtyRect {
    [super drawRect:dirtyRect];
    // Drawing code here.
    NSLog(@"drawRect is here");
    NSLog(@"drawRect aaa: %i", aaa);
    NSLog(@"drawRect nnn: %i", [nnn intValue]);
}
@end

我错过什么了吗?在Xcode 7.2&7.2.但如果我不勾选"使用故事板",它会起作用。

还是Xcode错误?

如有任何建议,不胜感激。提前谢谢。

如果在情节提要上添加了EEGView视图,则不应该同时在viewDidLoad中实例化一个视图。你已经分配了一个新的故事板,但它与故事板为你创建的故事板没有任何关系。因此,故事板创建的实例调用了drawRect,但您正在viewDidLoad中创建的单独实例中设置属性,该实例从未添加到视图层次结构中(因此永远不会调用其drawRect)。

当故事板实例化视图控制器的视图时,它将为您实例化EEGView。您所需要做的就是为该视图挂接一个IBOutlet,以便从视图控制器获得对它的引用。(例如,您可以控制从情节提要场景中的EEGView拖动到您在辅助编辑器中调出的视图控制器的@interface。)

最新更新