I have created a simple command line tool that outputs "hello world". This is done in the main() function.
In a separate application I can create a NSTask, pipe in the output from the hello world tool and use it successfully.
What I need my command line tool to do, though, is output something every second (I'm simplifying this). Elsewhere I have used an NSTimer for this with no problem, but creating an NSTimer in the main() function doesn't let me set 'self' as the target (I guess because it's not an object)?
What is the correct way to structure this? The tool just needs to output "hello world" every second until t开发者_开发技巧he process is stopped (by the application that launched it as an NSTask)?
What about the sleep()
function?
int main(...) {
while(1) {
printf("Hello world!\n");
sleep(1);
}
return 0;
}
How about NSThread's sleepForTimeInterval?
My approach would be to create a class (either separately or in the main.m file). To do so, write (under the #import statements)
@interface TimerClass : NSObject
/*class method, so "+" sign */ + (void) callFunction;
@end
then
@implementation TimerClass
. + (void)timerRespond:(NSTimer*)aTimer {
// call your command line tool
}
And in the main function, call NSTimer and make it have a time interval of 1 and call timerRespond of class TimerClass.
That should work fine (there might be some errors since I didn't check with Xcode). Tell me if it works. Good luck!
精彩评论