for loop execution doesn't permit touches on iPhone - iphone

Ok. I know the title may be confusing.
Logic That I have implemented is something like this.
There is an detector in application ( like bike speedometer - moving arrow )
When user taps start scan button - first method executes.
NowStartMovements decides random rotations & random number to stop
There are 1 to 10 numbers on detector.
Every thing works fine up to now.
Following code is error free.
Arrow moves perfectly & stops at proper position ( decided randomly )
But the problem is " I have implemented for loop for the movements "
So, while executing for loop, User interaction isn't enabled.
I have also added the code that I have implemented.
-(IBAction)ScanStart:(id)sender
{
btnScan.enabled=NO; stopThroughButtons=NO; shouldNeedleGoRightSide=YES; currentNeedleValue=1; nxtNeedleValue=2;
[NSTimer scheduledTimerWithTimeInterval:0 target:self selector:#selector(nowStartMovements) userInfo:nil repeats:NO];
}
-(void)nowStartMovements{
totalRotations=arc4random()%9; if(totalRotations<3) totalRotations+=3;
currentRotation=0;stopValue=arc4random()%11; if(stopValue<1)stopValue=1;
int totalMovements=(totalRotations-1)*10 + ( (totalRotations%2==0)?10-stopValue:stopValue ), i;
for(i=0;i<totalMovements;i++){
if (stopThroughButtons) return;
[NSThread detachNewThreadSelector:#selector(moveNeedle) toTarget:self withObject:nil];
usleep(200000);
}
}
-(void)moveNeedle{
spinAnimation = [CABasicAnimation animationWithKeyPath:#"transform.rotation.z"];
double fromValue=[[arrayOfFloatValues objectAtIndex:currentNeedleValue-1] doubleValue];
double toValue=[[arrayOfFloatValues objectAtIndex:nxtNeedleValue-1] doubleValue];
spinAnimation.duration=0.2;
spinAnimation.fromValue=[NSNumber numberWithFloat:fromValue];
spinAnimation.toValue = [NSNumber numberWithFloat:toValue];
[imgNideel.layer addAnimation:spinAnimation forKey:#"spinAnimation"];
[NSThread detachNewThreadSelector:#selector(MoveActualNeedle) toTarget:self withObject:nil];
}
-(void)MoveActualNeedle{
if(shouldNeedleGoRightSide){
if(currentNeedleValue<9) { currentNeedleValue++; nxtNeedleValue++;}
else { shouldNeedleGoRightSide=NO; currentNeedleValue=10; nxtNeedleValue=9;
}
imgNideel.transform=CGAffineTransformMakeRotation([[arrayOfFloatValues objectAtIndex:currentNeedleValue-1] doubleValue]);
} else {
if(currentNeedleValue>2){ currentNeedleValue--; nxtNeedleValue--;}
else { shouldNeedleGoRightSide=YES; currentNeedleValue=1; nxtNeedleValue=2;
}
imgNideel.transform=CGAffineTransformMakeRotation([[arrayOfFloatValues objectAtIndex:currentNeedleValue-1] doubleValue]);
}
}

You will need to rewrite your logic so it is the Timer that is doing the sleeping, not the usleep. Rewrite your function so that every iteration of the repeatable timer does what is in the for loop.
The problem is the for loop is sleeping on the main thread. If you use a timer and set repeats to YES, then this essesntially does the for/sleep pattern you are doing. When you want to stop it call [timer invalidate];

Ideally, you'd use a timer to schedule the needle movements. The quickest solution to your existing code is this:
In StartScan, change -scheduledTimerWithTimeInterval: to -performSelectorInBackground:
In nowStartMovements, change -detachNewThreadSelector: to -performSelectorOnMainThread:
This way, the usleep happens on a background thread and doesn't block the main thread. The UI will be frozen as long as the main thread is blocked.

Related

How can I use NSTimer with this simple while loop?

I have a -(void) method being executed and at one point it gets to a while loop that gets values from the accelerometer directly the moment it asks for them
I went throughout the documentation regarding the NSTimer class but I couldn't make sense of how exactly I am to use this object in my case :
e.g.
-(void) play
{
......
...
if(accelerationOnYaxis >0 && accelerationOnYaxis < 0.9 )
{
startTimer;
}
while(accelerationOnYaxis >0 && accelerationOnYaxis < 0.9)
{
if(checkTimer >= 300msec)
{
printOut_AccelerationStayedBetweenThoseTwoValuesForAtLeast300msecs;
break_Out_Of_This_Loop;
}
}
stopTimerAndReSetTimerToZero;
.....
more code...
....
...
}
Any help?
You cannot do it with NSTimer, because it needs your code to exit in order to fire. NSTimer uses the event loop to decide when to call you back; if your program holds the control in its while loop, there is no way for the timer to fire, because the code that checks if it's time to fire or not is never reached.
On top of that, staying in a busy loop for nearly a second and a half is going to deplete your battery. If you simply need to wait for 1.4s, you are better off calling sleepForTimeInterval:, like this:
[NSThread sleepForTimeInterval:1.4];
You can also use clock() from <time.h> to measure short time intervals, like this:
clock_t start = clock();
clock_t end = start + (3*CLOCKS_PER_SEC)/10; // 300 ms == 3/10 s
while(accelerationOnYaxis >0 && accelerationOnYaxis < 0.9)
{
if(clock() >= end)
{
printOut_AccelerationStayedBetweenThoseTwoValuesForAtLeast300msecs;
break_Out_Of_This_Loop;
}
}
NSTimer works a little different than you want. What you need is a counter for your timer, to get how many times it looped. If your counter gets on 14 (if it's an integer), you can invalidate it.
//start timer
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.1
target:self
selector:#selector(play:)
userInfo:nil
repeats:YES];
//stop timer
[timer invalidate];
You can create your function without that while.
- (void)play {
......
...
counter++; //declare it in your header
if(counter < 14){
x++; //your integer needs to be declared in your header to keep it's value
} else {
[timer invalidate];
}
useValueofX;
}
Take a look at the documentation.

objective-c: Animate button before timer ends

I'm working on a very simple iPhone game that involves choosing the right colored button as many times in a row based on a randomized voice prompt. I have it set up so that if the button is one color and gets clicked, it always goes to a hard-coded color every time (e.g. if you click red, it always turns blue). The color change method is set up in an IBOutlet. I have a timer set up in a while loop, and when the timer ends it checks if the player made the right selection. The problem is that the button color change does not occur until after the timer runs out, and this causes a problem with the method used to check the correct answer. Is there a way to make this color change happen instantly? From what I've searched I know it has something to do with storyboard actions not occurring until after code executes, but I haven't found anything with using a timer. Here is a section of the method that calls the timer if the answer is correct:
BOOL rightChoice = true;
int colorNum;
NSDate *startTime;
NSTimeInterval elapsed;
colorNum = [self randomizeNum:middle];
[self setTextLabel:colorNum];
while (rightChoice){
elapsed = 0.0;
startTime = [NSDate date];
while (elapsed < 2.0){
elapsed = [startTime timeIntervalSinceNow] * -1.0;
NSLog(#"elapsed time%f", elapsed);
}
rightChoice = [self correctChoice:middleStatus :colorNum];
colorNum = [self randomizeNum:middle];
}
One of two things stood out
You're using a while loop as a timer, don't do this - the operation is synchronous.
If this is run on the main thread, and you code doesn't return, your UI will update. The mantra goes: 'when you're not returning you're blocking.'
Cocoa has NSTimer which runs asynchronously - it is ideal here.
So let's get to grips with NSTimer (alternatively you can use GCD and save a queue to an ivar, but NSTimer seems the right way to go).
Make an ivar called timer_:
// Top of the .m file or in the .h
#interface ViewController () {
NSTimer *timer_;
}
#end
Make some start and stop functions. How you call these is up to you.
- (void)startTimer {
// If there's an existing timer, let's cancel it
if (timer_)
[timer_ invalidate];
// Start the timer
timer_ = [NSTimer scheduledTimerWithTimeInterval:5.0
target:self
selector:#selector(onTimerFinish:)
userInfo:nil
repeats:NO];
}
- (void)onTimerFinish:(id)sender {
NSLog(#"Timer finished!");
// Clean up the timer
[timer_ invalidate];
timer_ = nil;
}
- (void)stopTimer {
if (!timer_)
return;
// Clean up the timer
[timer_ invalidate];
timer_ = nil;
}
And now
Put your timer test code in the onTimerFinish function.
Make an ivar that stores the current choice. Update this ivar when a choice is made and make the relevant changes to the UI. Call stopTimer if the stop condition is met.
In the onTimerFinished you can conditionally call and startTimer again if you desire.
Hope this helps!

NSTimer firing instantly

I'm trying to develop a game and running into a small issue with NSTimer, once a sprite appear it has a certain amount on time in my scene before fading out.
double CALC_TIME = 5;
[NSTimer scheduledTimerWithTimeInterval:CALC_TIME target:self selector:#selector(hideSprite) userInfo:nil repeats:NO];
I want hideSprite to be called after 5 seconds, but instead it's called instantly(Or near instant).
A possible solution:
I know I could do this by setting the timer to repeat, and having a bool firstCall that is set first time and then the next interval the fading is done, the timer is invalidated but I don't think this is good practice
Like this:
bool firstCall = false;
-(void)hideSprite{
if(!firstCall){
firstCall = true
}else{
//fade out sprite
//Invalidate NSTimer
//firstCall = false;
}
}
Thanks for your help!
I suspect something else is calling hideSprite. The code you have written will cause the timer to wait for five seconds before calling the selector hideSprite.
Provide a different selector (write a new test method which just does an NSLog) to the timer and see what happens. This will tell you a) whether the timer is indeed immediately firing and b) if something else is calling hideSprite.
[NSTimer scheduledTimerWithTimeInterval:CALC_TIME target:self selector:#selector(testTimer) userInfo:nil repeats:NO];
-(void) testTimer { NSLog(#"Timer - and only the timer - called me."); }
-(void) hideSprite {
NSLog(#"I definitely wasn't called by the timer.");
}
Quite often it's easier to just use something like
[UIView animateWithDuration: 0 delay: 5 options:0 animations: nil completion:
^{
// fade sprite
}];
(not sure if animations can be nil, but you get the idea).
Consider initializing your timer using the initWithFireDate:interval:target:selector:userInfo:repeats method. Here is a more detailed look at NSTimer.

How can UI elements in iOS be updated from a loop without threads?

I want to update a label from a loop, for example like this:
- (void)viewDidLoad {
[super viewDidLoad];
int i=0;
while (1) {
i++;
[NSThread sleepForTimeInterval:0.05]; // do some computation,
[myLabel setText:[NSString stringWithFormat:#"%d", i]]; // show the result!
[self.view setNeedsDisplay];
}
}
Assume that instead of sleep some heavy computation is done.
I do not want the overhead of doing the computation in the background.
The Windows equivalent for handling this problem would be .DoEvents, as this example shows:
http://www.tek-tips.com/viewthread.cfm?qid=1305106&page=1
Is there a similar solution for this in iOS?
[self.view setNeedsDisplay] does not work at all!
There must be some way to process application events from iOS on a controlled schedule in the main thread... Like .DoEvents in windows, despite all its shortcomings is quite useful for some simple applications.
I guess this is like a game-loop but with UI components.
The way you would do this is as follows:
-(void) incrementCounter:(NSNumber *)i {
[myLabel setText:[NSString stringWithFormat:#"%d", [i intValue]]]; // show the result!
[self performSelector:#selector(incrementCounter:) withObject:[NSNumber numberWithInt:i.intValue+1] afterDelay:0.05];
}
- (void)viewDidLoad {
[super viewDidLoad];
// start the loop
[self incrementCounter:[NSNumber numberWithInt:0]];
}
The basic idea here is to increment the counter after a slight delay 0.05 to give the main UI thread a chance to flush all UI events, which makes up for explicitly calling .DoEvents in the Windows world.
I assume you want to implement a counter using a label? You can use NSTimer to call a method that updates your counter every X milliseconds, for instance.
Use NSTimer in iOS if you want to update UI components.
NSTimer* myTimer = [NSTimer scheduledTimerWithTimeInterval: 60.0 target: self
selector: #selector(callAfterSomeSecond:) userInfo: nil repeats: YES];
Implement the callAfterSomeSecond: as below :
-(void) callAfterSomeSecond:(NSTimer*) timer
{
static int counter = 0;
if(counter == 100)
{
[timer invalidate];
}
[myLabel setText:[NSString stringWithFormat:#"%d", counter ]];
[self.view layoutSubviews];
counter++;
}
in your code, the while loop runs in the Main thread, and the UI update also should be done in Main thread, so while the loop is running, the Main thread is kind of 'blocked'(busy), so UI update cannot be performed.
I think what I want to say is not what you want. to resolve it, you have to put the heavy computing in another thread, using NSOperation or GCD for example.
The best way is to do your computation on a different thread, but when that's not feasible, you can wrap the code that affects the UI in a CATransaction. In my tests this will update the UI immediately rather than needing to wait till the next run loop.
while (1) {
[CATransaction begin];
//Your UI code here
[CATransaction commit];
}

connectionDidFinishLoading - how to force update UIView?

I am able to download a ZIP file from the internet. Post processing is done in connectionDidFinishLoading and works OK except no UIView elements are updated. For example, I set statusUpdate.text = #"Uncompressing file" but that change does not appear until after connectionDidFinishLoading has completed. Similarly, the UIProgressView and UIActivityIndicatorView objects are not updated until this method ends.
Is there any way to force an update of the UIView from within this method? I tried setting [self.view setNeedsDisplay] but that didn't work. It appears to be running in the main thread. All other commands here work just fine - the only problem is updating the UI.
Thanks!
Update: here is the code that is NOT updating the UIVIEW:
-(void)viewWillAppear:(BOOL)animated {
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(processUpdate:) userInfo:nil repeats:YES];
downloadComplete = NO;
statusText.text = #"";
}
-(void)processUpdate:(NSTimer *)theTimer {
if (! downloadComplete) {
return;
}
[timer invalidate];
statusText.text = #"Processing update file.";
progress.progress = 0.0;
totalFiles = [newFiles count];
for (id fileName in newFiles) {
count++;
progress.progress = (float)count / (float)totalFiles;
// ... process code goes here ...
}
}
At then end of processUpdate, I set downloadComplete = YES. This builds & runs without errors and works as intended except nothing updates in the UIVIEW until after processUpdate completes, then everything updates at once.
Thanks for your help so far!
As Niels said, you must return control to the run loop if you want to see views update. But don't start detaching new threads unless you really need to. I recommend this approach:
- (void)connectionDidFinishLoading:(NSConnection *)connection {
statusUpdate.text = #"Uncompressing file";
[self performSelector:#selector(doUncompress) withObject:nil afterDelay:0];
}
- (void)doUncompress {
// Do work in 100 ms chunks
BOOL isFinished = NO;
NSDate *breakTime = [NSDate dateWithTimeIntervalSinceNow:100];
while (!isFinished && [breakTime timeIntervalSinceNow] > 0) {
// do some work
}
if (! isFinished) {
statusUpdate.text = // here you could update with % complete
// better yet, update a progress bar
[self performSelector:#selector(doUncompress) withObject:nil afterDelay:0];
} else {
statusUpdate.text = #"Done!";
// clean up
}
}
The basic idea is that you do work in small chunks. You return from your method to allow the run loop to execute periodically. The calls to performSelector: will ensure that control eventually comes back to your object.
Note that a risk of doing this is that a user could press a button or interact with the UI in some way that you might not expect. It may be helpful to call UIApplication's beginIgnoringInteractionEvents to ignore input while you're working... unless you want to be really nice and offer a cancel button that sets a flag that you check in your doUncompress method...
You could also try running the run loop yourself, calling [[NSRunLoop currentRunLoop] runUntilDate:...] every so often, but I've never tried that in my own code.
While you are in connectionDidFinishLoading nothing else happens in the application run loop. Control needs to be passed back to the run loop so it can orchestrate the UI updating.
Just flag the data transfer as complete and the views for updating. Defer any heavy processing of the downloaded data to it's own thread.
The application will call your views back letting them refresh their contents later in the run loop. Implement drawRect on your own custom views as appropriate.
If you're receiving connectionDidFinishLoading in the main thread, you're out of luck. Unless you return from this method, nothing will be refreshed in the UI.
On the other hand, if you run the connection in a separate thread, then you can safely update the UI using the following code:
UIProgressView *prog = ... <your progress view reference> ...
[prog performSelectorOnMainThread:#selector(setProgress:)
withObject:[NSNumber numberWithFloat:0.5f]
waitUntilDone:NO];
Be careful not to update the UI from a non-main thread - always use the performSelectorOnMainThread method!
Do exactly what you're doing with the timer, just dispatch your processing code to a new thread with ConnectionDidFinish:. Timers can update the UI since they're run from the main thread.
The problem turned out to that the UI isn't updated in a for() loop. See the answer in this thread for a simple solution!