1

I made an application which uses NSStream to etablish a connection to a telnet server. When the connection is made, I send a first command. Then I use sleep(1); to make my application wait. Then the second command is sent.

The problem is that the entire GUI is stuck during the sleep(). I know that it's not the "perfect" way to make a "pause" and I'd like to learn how to this properly. I heard good things about NSTimer but I'd like to have a concrete and "easy" way of using it, to simply replace my poor use of sleep().

jscs
  • 63,694
  • 13
  • 151
  • 195
Nono
  • 241
  • 5
  • 15
  • How are you making the connection? – jscs May 14 '12 at 00:15
  • Not only will it make your GUI unresponsive, it can(and probably eventually will) crash your GUI. Never perform sleeps on the main thread in Cocoa(doubly so for Cocoa touch) – user439407 May 14 '12 at 00:20
  • 1
    @user: On iOS, it's not a crash, it's the system killing your app because it's unresponsive. OS X doesn't have a watchdog timer like iOS does, and apps can be stalled or sleeping indefinitely. That said, you're right that one should not use `sleep()`, doubly so on iOS. – jscs May 14 '12 at 00:26

1 Answers1

1

You should be able to register some kind of callback with whatever procedure you're using to establish the connection. Just let your code wait for that callback without doing anything at all.

In this case, using NSStream, you need to schedule the stream on the run loop:

[stream scheduleInRunLoop:[NSRunLoop currentRunLoop]
                  forMode:NSDefaultRunLoopMode];

The run loop is the construct that processes events for your application. When you use sleep(), it is stopped, and your GUI can't do anything. By adding the stream as input to the run loop, you allow them both to continue to work.

You also must set a delegate object ([stream setDelegate:self];, e.g.) which will recieve notifications when the stream has something to report. That delegate must implement stream:handleEvent:, which will be called with a reference to the stream and a code indicating what happened.

jscs
  • 63,694
  • 13
  • 151
  • 195
  • So easy that I didn't think about it! I can wait the ">" char in the inputstream before sending my next command in the outputstream! With this way I'll have the "perfect" wait time! Thanks for your light! :) – Nono May 14 '12 at 00:21