I want to make a simples cliente of TCP. But I’m getting one error. When I make inputStream = (NSInputStream *)readStream; and outputStream = (NSOutputStream *)writeStream; it suggests me to introduce the prefix __bridge or _bridge_transfer.
First, what is it? Second, I tried both and still can’t send messages. I followed this tutorial and I’ve the send messages and stream too. I installed Wireshark and the send message is been called, but it’s not sending any packet to the ip.
I’ve just posted here the initNetworkCommunication because is where I get the “bridge” error.
- (void) initNetworkCommunication {
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"54.xxx.xxx.xxx", 1333, &readStream, &writeStream);
inputStream = (NSInputStream *)readStream;
outputStream = (NSOutputStream *)writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];
}
The server is fine, because i’ve tried the sample code and I get a response.
Can you help me?
As H2CO3 mentioned, it’s an ARC thing.
If you don’t know what ARC is, read this. To summarise, it’s a deterministic way of automating the memory management stuff (retain/release statements etc) that Objective-C programmers previously had to do manually. It’s well worth using, and has few downsides. However, it does have a few gotcha’s.
ARC doesn’t work on Core Foundation objects. They’re still subject to the old rules, where you have to do the memory management yourself. ARC only applies to Objective-C objects. However, some Core Foundation objects are actually toll-free bridged to their Cocoa equivalent. You’re using toll-free bridging in your code sample, to create a
CFReadStreamRefand then work with it as anNSInputStream.So what do you do? Apple’s docs say the following:
You’re moving from Core Foundation to Objective-C, so ignore the second bullet point (that’s for going in the other direction). The question is what do you want to happen — if after the transfer you want to hand that object to ARC, use it only from the Objective-C side, and have ARC deal with the memory management, use
__bridge_transfer. That’s probably what you want based on your code sample.If you just use
__bridge, or if you don’t use ARC, you’ll need to clear up the objects yourself, using eitherCFRelease()or by sending them areleasemessage (the latter only works if you’re not using ARC).