我想在自定義視圖中繪製某些東西,但不知道爲什麼drawRect無法訪問其實例數據。這是我嘗試的步驟。Xcode os x:爲什麼drawRect無法訪問實例數據
- 創建一個Mac OS X應用程序,並使用故事板檢查。
- 在故事板中,刪除視圖,然後在視圖下的同一位置添加新的自定義視圖。 (我試過,如果視圖沒有刪除,相同)。
- 將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錯誤?
任何意見讚賞。 在此先感謝。
無關手頭上的問題,但如果你創建具有'scheduledTimerWithTimeInterval'的計時器,您不必將其添加到運行循環中。它已經安排好了。如果你使用'timerWithTimeInterval'創建了定時器,那麼你將它添加到運行循環中,但是如果你已經安排了它,則不會。 – Rob
謝謝。得到它了。 – iSleep