asyncSocket writeData 使用不同的 NSData 崩溃
如果我用它来设置 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
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!
后者是空终止的,前者不是。这可能就是问题所在。
The latter is null terminated, the former is not. This is probably the issue.
我知道它有点晚了,但我认为最好知道为什么会这样 - 当您使用数据缓冲区调用 writeData 方法时,asyncsocket 代码通过使用传递下来的数据子类化 NSObject - AsyncWritePacket 来创建一个新对象。然后它使用保留并获取您正在传递的数据缓冲区的所有权,因此您不想释放它。
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.