Objective c 在两个不同的线程中运行两个NSStream
我的应用程序在一个单独的线程中运行一个网络任务——它从我的服务器获取数据,处理数据,并持续显示结果。当我在一个线程中只有一个这样的网络连接时,这种方法可以很好地工作。但是,如果我使用类似的网络任务运行第二个线程,则第二个线程工作正常,但第一个线程停止响应。我的类调度网络进程的代码如下所示。你有没有想过这里会出什么问题Objective c 在两个不同的线程中运行两个NSStream,objective-c,ios,nsthread,nsstream,cfstream,Objective C,Ios,Nsthread,Nsstream,Cfstream,我的应用程序在一个单独的线程中运行一个网络任务——它从我的服务器获取数据,处理数据,并持续显示结果。当我在一个线程中只有一个这样的网络连接时,这种方法可以很好地工作。但是,如果我使用类似的网络任务运行第二个线程,则第二个线程工作正常,但第一个线程停止响应。我的类调度网络进程的代码如下所示。你有没有想过这里会出什么问题 NSThread * nThread; - (NSThread *)networkThread { nThread = nil; nThread =
NSThread * nThread;
- (NSThread *)networkThread {
nThread = nil;
nThread =
[[NSThread alloc] initWithTarget:self
selector:@selector(networkThreadMain:)
object:nil];
[nThread start];
DLog(@"thread: %@, debug description: %@", nThread, nThread.debugDescription);
return nThread;
}
- (void)networkThreadMain:(id)unused {
do {
[[NSRunLoop currentRunLoop] run];
} while (YES);
}
- (void)scheduleInCurrentThread:(id)unused
{
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSRunLoopCommonModes];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSRunLoopCommonModes];
}
-(BOOL) connectWithError:(NSString **) e
{
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"127.0.0.1", [server port], &readStream, &writeStream);
inputStream = (__bridge NSInputStream *) readStream;
outputStream = (__bridge NSOutputStream *) writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[self performSelector:@selector(scheduleInCurrentThread:)
onThread:[self networkThread]
withObject:nil
waitUntilDone:YES];
[inputStream open];
[outputStream open];
}
1.是否使用该类的第二个实例来创建第二个连接?否则,第二个连接将覆盖实例变量
inputStream
和outputStream
-2.nThread
是这个类的实例变量还是局部变量?是的,当然,我使用这个类的另一个实例,所以inputSTream和outputStream是不同的对象。nThread是一个实例变量。请向上投票。谢谢你的帖子。不是问题,是你的代码把我带了上来。几个星期以来我一直在找这些东西。