The documentation for GCDAsyncSocket
says mutable data that might change should be copied before passing it to the write function.
In the following code:
func send(buffer: NSMutableData) {
let bufferCopy = NSData(data: buffer)
socket.writeData(bufferCopy, withTimeout: -1, tag: 0)
}
NSData
the right way to copy the buffer?bufferCopy
be retained in memory until writeData
(which is async
) finishes, or is it local to send, and destroyed when the function exits?1. Is the call to NSData the right way to copy the buffer?
Yes, it will copy the bytes to a new data object
2. Will bufferCopy be retained in memory until writeData (which is async) finishes, or is it local to send, and destroyed when the function exits?
Yes, it will be retained until writeData finishes. Also it will get deallocated once you return from the function send as there are no any other strong references to it from outside if writeData is synchronous. If WriteData is an async call, once the call is completed the data will be released as there won't be any strong ref to it as control would have come out from both send and the WriteData async call. So if this call is asynchronous, that means that call needs to have a strong ref to bufferCopy.