详情可官网查询NSStream用法
普通用法
- 读写文件
- 网络请求中inputStream用作request.HTTPBodyStream
-
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
如果设置了代理,stream内容没有处理完之前会不断调用该代理方法
BoundStream
- 写入OutPutStream的内容自动传输到InputStream
-
避免了一下子将所有内容读到内存中
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self setUpStreamForFile:nil];
...
request.HTTPBodyStream = iStream;
[oStream open];
[oStream write:[data1 bytes] maxLength:data1.length];
...
[oStream write:[data5 bytes] maxLength:data5.length];
[oStream close];
}
- (void)setUpStreamForFile:(NSString *)path {
// iStream是NSInputStream实例变量
NSInputStream *aiStream = [[NSInputStream alloc] init];
NSOutputStream *aoStream = [[NSOutputStream alloc] init];
[NSStream getBoundStreamsWithBufferSize:10240 inputStream:&aiStream outputStream:&aoStream];
iStream = aiStream;
oStream = aoStream;
[oStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[iStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
forMode:NSDefaultRunLoopMode];
}
自定义NSInputStream
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface MyInputStream : NSInputStream
@property (strong, nonatomic) NSInputStream *ownStream;
@end
NS_ASSUME_NONNULL_END
#import "MyInputStream.h"
@implementation MyInputStream
- (BOOL)hasBytesAvailable {
return [_ownStream hasBytesAvailable];
}
- (void)setDelegate:(id<NSStreamDelegate>)delegate {
}
- (NSStreamStatus)streamStatus {
return _ownStream.streamStatus;
}
- (void)open {
[_ownStream open];
}
- (void)close {
[_ownStream close];
}
- (NSInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)len {
return [_ownStream read:buffer maxLength:len];
}
- (id)propertyForKey:(__unused NSString *)key {
return nil;
}
- (BOOL)setProperty:(__unused id)property
forKey:(__unused NSString *)key
{
return NO;
}
- (void)scheduleInRunLoop:(__unused NSRunLoop *)aRunLoop
forMode:(__unused NSString *)mode
{}
- (void)removeFromRunLoop:(__unused NSRunLoop *)aRunLoop
forMode:(__unused NSString *)mode
{}
@end