I use NSInputstream
& NSOutputstream
to setup a connection and send data. My stream object has a function to open and close the stream. I use the following code:
@interface Stream()
{
NSInputStream *inputStream;
NSOutputStream *outputStream;
}
-(id)init
{
self = [super init];
if (self)
{
inputStream = nil;
outputStream = nil;
}
return self;
}
-(int)streamOpenWithIp:(NSString *)ip withPortNumber:(int)portNumber;
{
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, (__bridge CFStringRef)ip, portNumber, &readStream, &writeStream);
if(readStream && writeStream)
{
//Setup inpustream
inputStream = (__bridge NSInputStream *)readStream;
[inputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
//Setup outputstream
outputStream = (__bridge NSOutputStream *)writeStream;
[outputStream setDelegate:self];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream open];
}
}
- (int)streamClose;
{
CFReadStreamSetProperty((__bridge CFReadStreamRef)(inputStream), kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
CFReadStreamSetProperty((__bridge CFReadStreamRef)(outputStream), kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
//Close and reset inputstream
[inputStream setDelegate:nil];
[inputStream close];
[inputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
inputStream = nil;
//Close and reset outputstream
[outputStream setDelegate:nil];
[outputStream close];
[outputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
outputStream = nil;
}
This code works fine when I open and close the stream many times. When I check my app for memory leaks with Instruments, it said that the function CFStreamCreatePairWithSocketToHost
is leaking memory by 72%. Does someone know what I am doing wrong? I can't figure it out.