Fabio
Fabio

Reputation: 1973

Xcode NSTimer get position object every millisecond

I need to get the position of the _propArrow (UIImageView) every .1sec at all time and use a NSLog to verify in the method (void)runScheduledTask

but does not operate every .1 sec.

only indicates the start and end of the movement of the animation

This is my code:

- (void)viewDidLoad
{
    [super viewDidLoad];

    _propArrow.frame = CGRectMake(144, 291, 33, 71);


      aTimer = [NSTimer scheduledTimerWithTimeInterval:.1 target:self selector:@selector(runScheduledTask) userInfo:nil repeats:YES];



}


- (void)runScheduledTask {

  NSLog(@"Position: %@", NSStringFromCGRect(_propArrow.frame));

}


- (IBAction)fire:(id)sender {



[UIView animateWithDuration:1
                          delay:0
                        options:UIViewAnimationCurveEaseInOut
                     animations:^{

                              _propArrow.frame = CGRectMake(144, 0, 33, 71);
                     }
                     completion:^(BOOL finished){

                     }];



}

Upvotes: 0

Views: 1087

Answers (2)

tc.
tc.

Reputation: 33602

Because in most UIKit animated properties, the new value gets set immediately from the perspective of your code; it's the displayed value that actually animates. Reading animatable properties like UIView.frame should never give you an intermediate value (the main exception is UIScrollView which does its own thing for animated scrolling).

If you want "approximately what's being displayed on screen", you need to access the CoreAnimation "presentation layer":

#import <QuartzCore/CALayer.h>

- (void)runScheduledTask {
  NSLog(@"Position: %@", NSStringFromCGRect(_propArrow.layer.presentationLayer.frame));
}

Also consider using CADisplayLink if you want a callback that runs every frame.

Upvotes: 1

Caleb
Caleb

Reputation: 125037

First, according to the NSTimer docs, that class has an effective resolution of about 50-100 ms. So using it to do anything at 1 ms intervals is bound to fail.

Second, even if NSTimer could handle 1 ms intervals, you're not even asking it to do that:

aTimer = [NSTimer scheduledTimerWithTimeInterval:.05...

Your code schedules the timer to run ever 0.05 s, which is to say every 50 ms.

Third, the screen doesn't update at anything close to 1 ms intervals, so the actual position of your image on the screen will change much less often than that.

So, what exactly are you trying to accomplish here? If you want to know where the object would be in the real world with continuous motion, you can calculate that for any point in time.

Upvotes: 2

Related Questions