0

I want to create endless loop while button is clicked. Loop will break when I will press button again. I did something like this at the moment.

- (IBAction)Butt_uruchom:(id)sender {


    UIBarButtonItem *Button_Uruchom = (UIBarButtonItem *)sender;
    NSString *title=Button_Uruchom.title;
    if ([title isEqualToString:@"Start"])
    {


           Button_Uruchom.title = @"Stop";
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
        do{

            [self WyslijZapytanie:@"010C1\r\n"];

            }while([title isEqualToString:@"Stop"]);
        });


    }
    else
    {
        Button_Uruchom.title = @"Start";

    }

This code changes button title when button is clicked. I want to start loop when Start is pressed and stop when Stop is pressed. I tried to insert:

do{}while(title isEqualToString:@"Stop") in new Theard

in IF but it dosen't work. Could you help me make this? :)

Mateusz Tylman
  • 271
  • 1
  • 2
  • 17
  • Do not create an endless loop. It wastes CPU and battery. Refactor your code for proper event handling. – rmaddy Dec 21 '14 at 22:33
  • 1
    You don't need a loop here – pronebird Dec 21 '14 at 22:39
  • Objective c is event driven. You should NEVER be using loops like this. You should be responding to things that happen. Any sort of loop here is broken. – Fogmeister Dec 21 '14 at 22:42
  • So what should I do to make it work properly? I just want to continuously monitor parameter when I click Start button. So when Start is pressed program should send request till I press stop. – Mateusz Tylman Dec 21 '14 at 23:04
  • Ignoring design issues raised by others the error in your revised code is that you are testing `title` rather than `Button_Uruchom.title`. If you are going to do this consider adding a `BOOL` variable you set to `YES` in your `if` and to `NO` in your `else` - better than doing string comparison on each iteration. – CRD Dec 22 '14 at 01:30

2 Answers2

0

You can not loop for ever end receive button event on the same thread. Use a second thread. Start the thread on button click. Stop the thread on the second click. But in general it is unwise to loop for ever and waste CPU cicles.

  • I have edited my question with new code as you said. But it still doesn't work. I want to create loop for ever because I want to continuously monitor some parameter by socket connection. – Mateusz Tylman Dec 21 '14 at 21:37
0

please have a look at Understanding dispatch_async

to monitor a socket think about to use NSRunloop in your second thread. Runloop will put the threat to sleep until the source (e.g. socket) put's an event to the runloop

Community
  • 1
  • 1