gpt4 book ai didi

iphone - NSStreams 崩溃程序!

转载 作者:太空狗 更新时间:2023-10-30 03:33:14 24 4
gpt4 key购买 nike

全部,

我已经通过注释、断点等方式将它运行到这一点。程序在标记的代码处崩溃。

-(void) initNetworkCommunication
{
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"192.168.17.1", 2004, &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];//WHY MUST YOU CRASH HERE
[outputStream open];//WHY MUST YOU CRASH HERE ALSO!!?!?

NSLog(@"She be opened, sir!");
}

如果我注释掉这两个,它不会崩溃,但如果我注释掉其中一个,它就会崩溃(也就是说,它们都会导致程序崩溃)。调试器中也没有发布任何信息。它所做的就是将我发送到 main.m 并显示给我

“线程 1:程序收到信号:“EXC_BAD_ACCESS”。

提前感谢您的帮助!

编辑:这是我的委托(delegate)方法,但它甚至没有在日志中显示第二个事件行。

- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {

NSLog(@"stream event %i", streamEvent); //this doesn't post in the log when stream opened...

switch (streamEvent) {

case NSStreamEventOpenCompleted:
NSLog(@"Stream opened");
break;
case NSStreamEventHasBytesAvailable:

if (theStream == inputStream) {

uint8_t buffer[1024];
int len;

while ([inputStream hasBytesAvailable]) {
len = [inputStream read:buffer maxLength:sizeof(buffer)];
if (len > 0) {

NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];

if (nil != output) {

NSLog(@"server said: %@", output);
//[self messageReceived:output];

}
}
}
}
break;


case NSStreamEventErrorOccurred:

NSLog(@"Can not connect to the host!");
break;

case NSStreamEventEndEncountered:

[theStream close];
[theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
//[theStream release];
theStream = nil;

break;
default:
NSLog(@"Unknown event");
}

}

最佳答案

正在发生的事情是委托(delegate)类的实例正在被释放(在运行循环中导致 EXC_BAD_ACCESS),要么是因为您没有保留它,要么是因为您正在使用 ARC(很可能)并且您没有引用给它。

解决方案是在委托(delegate)类上调用 retain,大致如下:

SomeStreamDelegate *theDelegate = [[SomeStreamDelegate alloc] init];
[theDelegate retain];

或者,如果您确实启用了 ARC,请在您分配委托(delegate)的类中创建一个实例变量,并将您的连接实例存储在那里。这样 ARC 就不会释放它,因为实例 var 算作一个引用。

关于iphone - NSStreams 崩溃程序!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6686441/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com