tags:

views:

167

answers:

3

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 the process is stopped (by the application that launched it as an NSTask)?

+2  A: 

What about the sleep() function?

int main(...) {
  while(1) {
    printf("Hello world!\n");
    sleep(1);
  }
  return 0;
}
Dave DeLong
I thought about that - so that would be an ok way to do it? Just loop a sleep command until the process is terminated? Maybe I've just spent too long with my head in it and lost track of the simple solution.How would I replace the printf statement with a call to another function outside main, and where would I put this function? Directly below main()? Not sure of the syntax, or where to look - this feels more like C programming more than OO now, which is fine but not something I've done since college!
Ben Packard
You're using Objective-C, so create an object, import its header into `main.m` and instantiate it in `main()` using `[[YourObject alloc] init]`. You can then work with it like you would in any Cocoa app. Make sure you have an autorelease pool in place, or that you have called `objc_startCollectorThread()` if you want the tool to be garbage-collected.
Rob Keniger
Wonderful - up and running - thanks!
Ben Packard
+2  A: 

How about NSThread's sleepForTimeInterval?

SoloBold
A: 

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!

Alexandre Cassagne