- iOS 2.0+
- macOS 10.3+
- tvOS 9.0+
- watchOS 2.0+
NSStream objects provide an easy way to read and write data to and from a variety of media in a device-independent way. You can create stream objects for data located in memory, in a file, or on a network (using sockets), and you can use stream objects without loading all of the data into memory at once.
NSStream instances that are not file-based are nonseekable, one-way streams (although custom seekable subclasses are possible). Once the data has been provided or consumed, the data cannot be retrieved from the stream.
NSStream is an abstract class, incapable of instantiation and intended to be subclassed. It publishes a programmatic interface that all subclasses must adopt and provide implementations for. The two Apple-provided concrete subclasses of
NSOutput, are suitable for most purposes. However, there might be situations when you want a peer subclass to
NSOutput. For example, you might want a class that implements a full-duplex (two-way) stream, or a class whose instances are capable of seeking through a stream.
Methods to Override
All subclasses must fully implement the following methods, which are presented in functional pairs:
opento open the stream for reading or writing and make the stream available to the client directly or, if the stream object is scheduled on a run loop, to the delegate. Implement
closeto close the stream and remove the stream object from the run loop, if necessary. A closed stream should still be able to accept new properties and report its current properties. Once a stream is closed, it cannot be reopened.
Return and set the delegate. By a default, a stream object must be its own delegate; so a
delegatemessage with an argument of
nilshould restore this delegate. Do not retain the delegate to prevent retain cycles.
To learn about delegates and delegation, read "Delegation" in Cocoa Fundamentals Guide.
scheduleto schedule the stream object on the specified run loop for the specified mode. Implement
In Run Loop: for Mode:
removeto remove the object from the run loop. See the documentation of the
From Run Loop: for Mode:
NSRunclass for details. Once the stream object for an open stream is scheduled on a run loop, it is the responsibility of the subclass as it processes stream data to send
stream:messages to its delegate.
Implement these methods to return and set, respectively, the property value for the specified key. You may add custom properties, but be sure to handle all properties defined by
streamto return the current status of the stream as a NSStreamStatus constant; you may define new NSStreamStatus constants, but be sure to handle the
NSStream-defined constants properly. Implement
streamto return an
NSErrorobject representing the current error. You might decide to return a custom
NSErrorobject that can provide complete and localized information about the error.