facebookincubator / SocketRocket

A conforming Objective-C WebSocket client library.
Other
9.56k stars 2.01k forks source link

weak/strong self bug in SRProxyConnect _writeData #517

Open peternlewis opened 7 years ago

peternlewis commented 7 years ago

Note that the variable wself is never actually used, except to get it's type "typeof(wself)".

The line should be:

    __strong typeof(wself) sself = wself;
dumganhar commented 7 years ago

Is sself needed? Could we just use wself directly? e.g.

   __weak __typeof(self) wself = self;
    dispatch_async(_writeQueue, ^{
        if (!wself) {
            return;
        }
        NSOutputStream *outStream = wself.outputStream;
        if (!outStream) {
            return;
        }
    ...
}
dumganhar commented 7 years ago

And SRProxyConnect will not retain the block in _writeData, there will not be any cycle reference. Therefore, is __weak actually needed?

dumganhar commented 7 years ago

OK, I got it. If we don't assign a weak object to strong, there will be a warning:

weak variable 'wself' is accessed multiple times in this block but may be unpredictably set to nil; assign to a strong variable to keep the object alive [-Warc-repeated-use-of-weak]

peternlewis commented 7 years ago

Yes, you've worked through it all.

You are right that you could just use self in the block if you're happy for the async block to keep the connection retained until it executes, rather than doing nothing if the connection is otherwise released, but probably the latter behaviour is better, thus the weak/strong dance.