asyncSocket writeData 使用不同的 NSData 崩溃

发布于 2024-11-18 00:32:59 字数 568 浏览 3 评论 0原文

如果我用它来设置 NSData 那么 writeData 方法就会崩溃。

   NSString *test = @"The quick brown fox jumped over the lazy dog\r\n";
   NSData *data = [test dataUsingEncoding:NSUTF8StringEncoding];

   [asyncSocket writeData:data withTimeout:10 tag:4];

但是,如果我使用这个,那么它就可以工作...但是我需要 NSString,以便我可以输入要发送的格式化字符串...

 char bytes[] = "The quick brown fox jumped over the lazy dog\r\n";
 NSData* data = [[NSData alloc] initWithBytes:bytes length:sizeof(bytes)];

 [asyncSocket writeData:data withTimeout:10 tag:4];

那么我做错了什么?

If I use this to set up NSData then the writeData method crashes.

   NSString *test = @"The quick brown fox jumped over the lazy dog\r\n";
   NSData *data = [test dataUsingEncoding:NSUTF8StringEncoding];

   [asyncSocket writeData:data withTimeout:10 tag:4];

However if I use this one then it works... but I need the NSString so I can enter a formatted string to send...

 char bytes[] = "The quick brown fox jumped over the lazy dog\r\n";
 NSData* data = [[NSData alloc] initWithBytes:bytes length:sizeof(bytes)];

 [asyncSocket writeData:data withTimeout:10 tag:4];

So what did I do wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

じее 2024-11-25 00:32:59

NSString 和 NSDate 没有使用 alloc 和 init 设置,因此当它们到达写入数据时它们就消失了。我将 NSDate 更改为 alloc 和 init,现在一切正常。这个想法来自于回答这个问题的几个人。感谢您的帮助!

The NSString and the NSDate were not setup with alloc and init so they were gone when they got to the write data. I changed the NSDate to alloc and init and all works well now. These idea came from the several people that answered this. thanks for the help!

一花一树开 2024-11-25 00:32:59

后者是空终止的,前者不是。这可能就是问题所在。

The latter is null terminated, the former is not. This is probably the issue.

谜兔 2024-11-25 00:32:59

我知道它有点晚了,但我认为最好知道为什么会这样 - 当您使用数据缓冲区调用 writeData 方法时,asyncsocket 代码通过使用传递下来的数据子类化 NSObject - AsyncWritePacket 来创建一个新对象。然后它使用保留并获取您正在传递的数据缓冲区的所有权,因此您不想释放它。

@implementation AsyncWritePacket
- (id)initWithData:(NSData *)d timeout:(NSTimeInterval)t tag:(long)i
{
    if((self = [super init]))
    {
        buffer = [d retain];
        timeout = t;
        tag = i;
        bytesDone = 0;
    }
    return self;

@end

I know its bit late but I thought it would be good to know why this works - When you call writeData method with your data buffer, the asyncsocket code creates a new object by sublassing NSObject - AsyncWritePacket using the data passed down. It then uses retain and takes ownership of the data buffer you are passing hence why you dont want to release it.

@implementation AsyncWritePacket
- (id)initWithData:(NSData *)d timeout:(NSTimeInterval)t tag:(long)i
{
    if((self = [super init]))
    {
        buffer = [d retain];
        timeout = t;
        tag = i;
        bytesDone = 0;
    }
    return self;

@end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文