NSStream.getStreamsToHostWithName导致内存泄漏

时间:2014-12-26 08:13:41

标签: swift nsstream

我可以连接到twitch的聊天并来回发送消息,但是我注意到每次连接时都会有少量内存泄露

以下是导致泄漏的代码的核心。 (通过多次调用此方法,空应用程序的已用内存从12MB变为超过100MB)

@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
    }
}

但是,使用旧方法时没有泄漏,这在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
    }
}

有没有办法清理内存,还是我必须再继续使用旧方法?

1 个答案:

答案 0 :(得分:3)

我试图在1月份就这个问题与Apple联系,今天刚收到回复。解决方案是在autoreleasepool调用周围添加NSStream.getStreamsToHostWithName,这会导致NSStream内容在块完成后立即释放,而不是在某个时间后#39 ;这往往是在遥远的未来。