NSPipe

Instances of NSPipe represent a one-way channel for communication between two tasks. While one task pours data into one end of the pipe, another process reads that data out. You can create a pipe in two ways: with the convenience constructor pipe or with alloc and init. Every pipe has a read and a write end that objects connect to by retrieving NSFileHandle instances using the methods fileHandleForReading and fileHandleForWriting.

NSPipe is also buffered , which means that it can store data poured into the write end of the pipe up to a maximum amount that is defined by the underlying operating system. Example 7-1 shows you how to create a pipe by using NSPipe and NSTask.

Example 7-1. Using NSPipe to get data from an NSTask instance
                  // Instantiate and initialize a new task
NSTask *task = [[NSTask alloc] init];

// Create a pipe to communicate with the task
NSPipe *pipe = [[NSPipe alloc] init];

// Get a file handle to read from the pipe
NSFileHandle *readEnd = [pipe fileHandleForReading];

// Set the path to launch the task at
[task setLaunchPath:@"/bin/ls"];

// Set the arguments; ls takes the directory to list
[task setArguments:[NSArray arrayWithObject:@"/"]];

// Connect the pipe to the task's stdout
[task setStandardOutput:pipe];

// Launch the task
[task launch];

// Once it's launched we can read data from the pipe
NSData *stdOutData = [readEnd availableData];
NSLog(@"%s", [stdOutData bytes]);

Distributed Notifications

As noted in Chapter 2, the Foundation framework’s notification ...

Get Cocoa in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.