2016-03-28 86 views
1

我想在自定義視圖中繪製某些東西,但不知道爲什麼drawRect無法訪問其實例數據。這是我嘗試的步驟。Xcode os x:爲什麼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錯誤?

任何意見讚賞。 在此先感謝。

+0

無關手頭上的問題,但如果你創建具有'scheduledTimerWithTimeInterval'的計時器,您不必將其添加到運行循環中。它已經安排好了。如果你使用'timerWithTimeInterval'創建了定時器,那麼你將它添加到運行循環中,但是如果你已經安排了它,則不會。 – Rob

+0

謝謝。得到它了。 – iSleep

回答

0

如果您在故事板上添加了EEGView視圖,則不應該在viewDidLoad中實例化一個視圖。你已經分配/初始化了一個新的,但它與故事板爲你創建的那個沒有關係。所以,故事板創建的那個被調用drawRect,但是您在您創建的單獨實例中設置了屬性,該實例在viewDidLoad中從未添加到視圖層次結構(因此永遠不會調用它的drawRect)。

當故事板實例化視圖控制器的視圖時,它會爲您實例化您的EEGView。所有你需要做的就是爲這個視圖掛上一個IBOutlet,以便從你的視圖控制器獲得對它的引用。 (例如,您可以控制從EEGView拖動至情節板中的場景到@interface爲您在助理編輯拉昇視圖控制器)。

+0

是的,你是對的。謝謝! – iSleep

相關問題