Reputation: 18122
I have a shell script logging a list of numbers (1, 2, and so forth, one per line) to a log file. I need my ObjC app to read the log file every X seconds and then update my progress bar accordingly based on the last number logged in the log file.
What's the best way to do this?
Upvotes: 1
Views: 1083
Reputation: 96333
Why not use NSFileHandle's readInBackgroundAndNotify
instead? This way, your code only runs when something really does happen in the file.
Upvotes: 4
Reputation: 60130
You can create an instance of NSTimer and have it, every X seconds, call another method that's responsible for reading the file and updating your progress bar. That method can use NSString's stringWithContentsOfFile:
to read the file into a string, then parse it appropriately.
For example:
// Create the invocation of the method to call
NSUInteger X = 2; // Change depending on how often you want the timer fired
NSMethodSignature *signature = [self methodSignatureForSelector:@selector(read)];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
// Create the timer, adding it to the default run loop
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:X
invocation:invocation
repeats:YES];
And later, you define the selector read
:
- (void)read {
NSString *fileContents = [NSString stringWithContentsOfFile:@"aFile.txt"];
NSArray *lines = [fileContents componentsSeparatedByString:@"\n"];
NSString *lastLine = [lines lastObject];
// Your own parsing and updating code here
}
If you need a definite stopping point, you can store timer
in an ivar inside your class, then call [timer invalidate];
whenever your parsing code inside read
determines you're done with whatever process you're executing.
Relevant docs:
scheduledTimerWithTimeInterval:invocation:repeats:
invocationWithMethodSignature:
methodSignatureForSelector:
Upvotes: 0