I am able to connect to twitch's chat and send messages back and forth, however I noticed that every time I connect there is a small amount of memory that gets leaked
Here is the core of the code that is causing the leak. (The used memory of the empty app goes from 12MB to over 100MB by only calling this method multiple times)
@IBAction func lotsOfConnects(sender: NSButton) {
for i in 0..<10_000 {
var readStream: NSInputStream?
var writeStream: NSOutputStream?
NSStream.getStreamsToHostWithName("irc.twitch.tv", port: 6667, inputStream: &readStream, outputStream: &writeStream)
// Leaks with of without these two lines
readStream = nil
writeStream = nil
}
}
However, there is no leak when using the old method which is not as nice in Swift
@IBAction func j(sender: NSButton) {
for i in 0..<10_000 {
var readStream: Unmanaged<CFReadStream>?
var writeStream: Unmanaged<CFWriteStream>?
CFStreamCreatePairWithSocketToHost(nil, "irc.twitch.tv", 6667, &readStream, &writeStream)
var inputStream = readStream!.takeRetainedValue()
var outputStream = writeStream!.takeRetainedValue()
readStream = nil
writeStream = nil
}
}
Is there a way to clean up the memory, or do I have to continue using the old method a while longer?
I tried to contact Apple back in January about this issue, and just received a response today. The solution is to add autoreleasepool
around the NSStream.getStreamsToHostWithName
call, which causes the NSStream stuff to be deallocated as soon as the block finishes rather than 'sometime later' which tends to be in the distant future.