Reputation:
Best all,
I am writing an app in Xcode 5.1.1 and objective-c.
In the app there is (for testing) only one button right now. When I click the button it has to run a piece of code forever. When I click the button again I want the same piece of code stop running. And when I touch it again it start running again. I have tried it with a simple for loop, but this does not work (predictable of course). When I touch the button it starts running, but then the view becomes unusable. How can I accomplish this?
Upvotes: 0
Views: 140
Reputation: 6524
You can simply use NSTimer
:
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(yourMethod:) userInfo:nil repeats:YES];
And in the button action "@selector
" user:
[timer invalidate];
EDIT:
As you can read from the comments, Using a timer to run something forever can be dangerous, make certain the time interval is longer than the script (or piece of code) is running for. Otherwise you'll potentially load down your CPU with thousands of identically running scripts pretty quickly
Upvotes: 1
Reputation: 100
I never realy develop in objective-c but i would write an class that extends Thread and then in this class i would put an volatile static variable that indicates it the button was clicked. In the run method i would take a while loop while the var is false run the code and if it turn true exit or viceversa. Whenever the button is clicked i would switch the var and start the thread. So it gets executed if the button was clicked every second time.
I would write it as an comment but have no permissions..
Upvotes: 0
Reputation: 11
The key is to run the code in the background so it doesn't mess up your user interface. You can do this using
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// your code
});
Upvotes: 0