Reputation: 27598
This was pretty werid and I am sure I am missing something basic here.
What I have are
What happening is that when I press button1 then for-loop starts. I cannot press any more buttons on the screen till this for-loop ends i.e. I cannot press down on button2.
How can I make it so that when I press button1 I still have the ability to cancel that for-loop action of button1 by pressing button2. Here is my code
static bool scanCancelled = NO;
-(IBAction)startAction
{
for (int i=0; i<5000; i++)
{
NSLog(@"i: %d ...", i);
if (scanCancelled == YES)
{
break;
}
}//end for-loop
}
-(IBAction)cancelAction
{
scanCancelled = YES;
}
For anyone interested in future this is how I did it
-(IBAction)startAction2
{
//reset it
scanCancelled = NO;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,
(unsigned long)NULL), ^(void) {
[self startAction];
});
}
Upvotes: 2
Views: 182
Reputation: 816
As others have said, you have to use another thread/process to run the long running for loop, so the UI can continue handling events, etc.
But I don't recommend using the threading classes in iOS, which can seem a little obtuse unless you are used to multi-threading*, instead I recommend using Grand Central Dispatch: https://developer.apple.com/library/ios/documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html
Using it is quite easy and will introduce you to blocks, which are very powerful. Here is a tutorial to get you started: http://www.raywenderlich.com/4295/multithreading-and-grand-central-dispatch-on-ios-for-beginners-tutorial
*That all being said, you should look into typical threading models and how they work. The concepts are in use well beyond iOS and Objective-C.
Upvotes: 2
Reputation: 10254
You will have to run that long running operation from a separate thread to open the Main UI Thread for user interaction.
Then you can send a cancel message to your other thread from the action of button 2.
Upvotes: 0