objective-c - Cocoa、免费桥接和 ARC

标签 objective-c cocoa stream inputstream tcpclient

我想制作一个简单的 TCP 客户端。但我收到一个错误。当我制作 inputStream = (NSInputStream *)readStream;outputStream = (NSOutputStream *)writeStream; 时,它建议我引入前缀 __bridge 或 _bridge_转移。

首先,它是什么?其次,我都尝试了,仍然无法发送消息。我关注了这个tutorial我也有发送消息和流媒体。我安装了 Wireshark 并调用了发送消息,但它没有向该 IP 发送任何数据包。

我刚刚在这里发布了 initNetworkCommunication,因为这是我收到“bridge”错误的地方。

- (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];

}

服务器很好,因为我已经尝试了示例代码并且得到了响应。

你能帮我吗?

最佳答案

正如 H2CO3 提到的,这是一个 ARC 事物。

如果您不知道 ARC 是什么,read this 。总而言之,它是一种确定性的自动化内存管理内容(保留/释放语句等)的方法,而 Objective-C 程序员以前必须手动执行这些操作。它非常值得使用,并且几乎没有缺点。然而,它确实有一些问题。

ARC 不适用于 Core Foundation 对象。它们仍然受到旧规则的约束,您必须自己进行内存管理。 ARC仅适用于Objective-C对象。然而,一些 Core Foundation 对象实际上是免费桥接到它们的 Cocoa 等价物的。您在代码示例中使用免费桥接来创建 CFReadStreamRef然后将其用作 NSInputStream .

那你做什么呢? Apple 的文档如下:

If you cast between Objective-C and Core Foundation-style objects, you need to tell the compiler about the ownership semantics of the object using either a cast (defined in objc/runtime.h) or a Core Foundation-style macro (defined in NSObject.h):

  • __bridge transfers a pointer between Objective-C and Core Foundation with no transfer of ownership.
  • __bridge_retained or CFBridgingRetain casts an Objective-C pointer to a Core Foundation pointer and also transfers ownership to you. You are responsible for calling CFRelease or a related function to relinquish ownership of the object.
  • __bridge_transfer or CFBridgingRelease moves a non-Objective-C pointer to Objective-C and also transfers ownership to ARC. ARC is responsible for relinquishing ownership of the object.

您正在从 Core Foundation 转向 Objective-C,因此请忽略第二个要点(即朝另一个方向前进)。问题是你想要发生什么 - 如果在传输之后你想将该对象交给 ARC,仅从 Objective-C 端使用它,并让 ARC 处理内存管理,请使用 __bridge_transfer 。根据您的代码示例,这可能就是您想要的。

如果你只是使用__bridge ,或者如果您不使用 ARC,则需要自己清理对象,使用 CFRelease()或者给他们发送 release消息(后者仅在您不使用 ARC 时才有效)。

关于objective-c - Cocoa、免费桥接和 ARC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11469220/

相关文章:

objective-c - NSSharingService 与 GIF 动画?

macos - 带 https 和 TLS 1.1 的 NSURLConnection

java - 使用 Esper,如何对事件进行动态过滤?

ios - 允许 iOS http 直播流和流

ios - 什么值会在文本字段上显示为无穷大?

ios - 我可以使用 NSMutableArray insertObjects :atIndexes to insert multiple items in different order?

objective-c - nsarray 中自定义对象 NSString 属性的唯一值

swift - NSNumberFormatterStyle.SpellOutStyle 中的错误?

iphone - 服务器未提出质询时的 NSURL 身份验证

c++ - 将对象数组写入和读取到二进制文件?