Line Filters in Objective-C

A line filter is a common type of program that reads input on stdin, processes it, and then prints some derived result to stdout. grep and sed are common line filters.

Here’s an example line filter in Objective-C that writes a capitalized version of all input text. You can use this pattern to write your own Objective-C line filters.

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // Create an NSFileHandle for standard input
        NSFileHandle *input = [NSFileHandle fileHandleWithStandardInput];
        
        // Read all the input data
        NSData *inputData = [input readDataToEndOfFile];
        
        // Convert the data to a string
        NSString *inputString = [[NSString alloc] initWithData:inputData encoding:NSUTF8StringEncoding];
        
        // Split the input into lines
        NSArray *lines = [inputString componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
        
        // Process each line
        for (NSString *line in lines) {
            // Convert the line to uppercase
            NSString *uppercaseLine = [line uppercaseString];
            
            // Print the uppercase line
            NSLog(@"%@", uppercaseLine);
        }
    }
    return 0;
}

In this Objective-C version:

  1. We use NSFileHandle to read from standard input.
  2. We read all the input data at once using readDataToEndOfFile.
  3. We convert the input data to a string and split it into lines.
  4. We iterate over each line, convert it to uppercase, and print it.

To check for errors, we could add error handling around the file operations, but for simplicity, this example assumes the input will be valid.

To try out our line filter, first make a file with a few lowercase lines.

$ echo 'hello'   > /tmp/lines
$ echo 'filter' >> /tmp/lines

Then use the line filter to get uppercase lines. Assuming you’ve compiled the Objective-C program to an executable named line-filter:

$ cat /tmp/lines | ./line-filter
HELLO
FILTER

Note that NSLog adds a timestamp to each line by default. To get clean output without timestamps, you could replace NSLog(@"%@", uppercaseLine); with printf("%s\n", [uppercaseLine UTF8String]);.

This Objective-C version provides similar functionality to the original example, reading input line by line, processing it, and writing the result to stdout.