我只是在几秒钟后关闭NSPanel,但我无法启动我的NSTimer。如果我明确地调用它的fire方法,它会启动,但它永远不会自行完成。这里是我的代码:NSTimer永远不会启动
- (void)startRemoveProgressTimer:(NSNotification *)notification {
NSLog(@"timer should start");
timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(removeProgress:) userInfo:nil repeats:NO];
}
- (void)removeProgress:(NSTimer *)timer {
[progressPanel close];
}
我确实在我的代码中有一些线程。我认为这是搞乱我的计时器了。
-(void)incomingTextUpdateThread:(NSThread*)parentThread {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
//mark the thread as running
readThreadRunning = TRUE;
const int BUFFER_SIZE = 100;
char byte_buffer[BUFFER_SIZE]; //buffer for holding incoming data
int numBytes = 0; //number of bytes read
NSString *text; //incoming text from the serial port
[NSThread setThreadPriority:1.0];
//this will loop until the serial port closes
while (TRUE) {
//read() blocks until some data is available or the port is closed
numBytes = read(serialFileDescriptor, byte_buffer, BUFFER_SIZE);
if(numBytes > 0) {
//creat a string from the incoming bytes
text = [[[NSString alloc] initWithBytes:byte_buffer length:numBytes encoding:[NSString defaultCStringEncoding]] autorelease];
if(!([text rangeOfString:SEND_NEXT_COORDINATE].location == NSNotFound)) {
//look for <next> to see if the next data should be sent
if(coordinateNum <[coordinatesArray count]) {
[self sendNextCoordinate]; //send coordinates
}
else {
[self writeString:FINISH_COORDINATES_TRANSMIT]; //send <end> to mark transmission as complete
NSNumber *total = [NSNumber numberWithUnsignedInteger:[coordinatesArray count]];
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:total forKey:@"progress"];
[[NSNotificationCenter defaultCenter] postNotificationName:@"uploadProgressChange" object:self userInfo:userInfo]; //update progress bar to completed
}
}
[self performSelectorOnMainThread:@selector(appendToIncomingText:) withObject:text waitUntilDone:YES]; //write incoming text to NSTextView
} else {
break; //Stop the thread if there is an error
}
}
// make sure the serial port is closed
if (serialFileDescriptor != -1) {
close(serialFileDescriptor);
serialFileDescriptor = -1;
}
// mark that the thread has quit
readThreadRunning = FALSE;
// give back the pool
[pool release];
}
从另一方法,通过调用:[self performSelectorInBackground:@selector(incomingTextUpdateThread:) withObject:[NSThread currentThread]];
嗯......没有看到任何错误,但你为什么要传递currentThread作为withObject:参数?你似乎没有用这种方法,为什么不通过零? – jakev
怀疑我有(只是怀疑,因为我看不到是什么调用startRemoveProgressTimer :) scheduledTimerWithTimeInterval将计时器添加到当前线程的运行循环,而不是主线程。如果你正在后台线程中创建你的定时器,它永远不会使用它的运行循环 - 如果只是从一个文件描述符的while(1)循环读取中坐下并旋转,说 - 运行循环永远不会有机会处理任何排队的定时器。试着明确地将它添加到主线程的运行循环中,看看会发生什么。 – rgeorge
如果我告诉你startRemoveProgressTimer:是否与NSNotification绑定,它会有所作为吗?至于为什么我在当前线程中传递,我不确定。我正在尝试将别人的代码调整到我的应用程序中。原始代码在这里:http://arduino.cc/playground/Interfacing/Cocoa,但我必须做一些修改才能在(Snow)Leopard上编译它,并且我加入了一些我自己的逻辑。 –