I'll explain my problem. I need to maintain a tcp connection while my app is running, so I need to have regard to the connection on a background thread. I use the following to connect the socket and works well.
on connection.m
myThread = [[NSThread alloc] initWithTarget:self selector:@selector(Connect) object:nil];
[myThread start];
-(void)Connect {
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)IP,PORT, &readStream, &writeStream);
inputStream = (__bridge NSInputStream *)readStream;
outputStream =(__bridge NSOutputStream *)writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];
[[NSRunLoop currentRunLoop] run];
}
-(void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {
//all the code to receive data
}
Now, the connection is working on a different thread to main thread. and I know that if I send something to the main thread I can use this,
performSelectorOnMainThread
or
dispatch_async(dispatch_get_main_queue(), ^{ ... do stuff
but if what I want is to send something through the outputstream by pressing a button in my view, the function is called,but outputstream is null. I think is because isn't in the thread where the connection is running.
how I can make that function is executed in the thread where I have the connection?
any help is well appreciated
Can you just use performSelector:OnThread:?