Invoke an action at specific intervals in iOS

I am trying to call a function containing ccactioninterval in Cocos3d . I want to call this function at regular intervals. When I tried NSTimer , I found that it works sometimes, and sometimes not.

NSTimer makeTarget=[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(createTargets) userInfo:nil repeats:YES]; 

Here createTargets is a function that contains action events. when I run the straightit function, it works fine for once. The problem arises when I try to plan it. I tried different methods already explained for related questions. But nothing worked for me.,.

Here is the code

 -(void) addTargets { NSTimer *makeTarget = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(createTargets) userInfo:nil repeats:YES]; } -(void)createTargets { CC3MeshNode *target = (CC3MeshNode*)[self getNodeNamed: @"obj1"]; int minVal=-5; int maxVal=5; float avgVal; avgVal = maxVal- minVal; float Value = ((float)arc4random()/ARC4RANDOM_MAX)*avgVal+minVal ; [target setLocation:cc3v(Value, 5.0, 0.0)]; CCActionInterval *moveTarget = [CC3MoveBy actionWithDuration:7.0 moveBy:cc3v(0.0, -10.0, 0.0)]; CCActionInterval *removeTarget = [CCCallFuncN actionWithTarget:self selector:@selector(removeTarget:)]; [target runAction:[CCSequence actionOne:moveTarget two:removeTarget]]; } -(void)removeTarget:(CC3MeshNode*)targ { [self removeChild:targ]; targ=nil; } 
+4
source share
1 answer

Without a lot of code, it's hard to say what you are doing, but here are some things to try to apologize if this is obvious.


Do you keep a link to a timer?

This can be useful for debugging. If you have a property called makeTargetTimer , you can do this:

 NSTimer * makeTargetTimer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(createTargets) userInfo:nil repeats:YES]; self.makeTargetTimer = makeTargetTimer // Save to a property for later use (or just use an iVar) 

The only way to stop the re-timer is to invalidate it. Therefore, you can check to see if it was invalid.

 BOOL isInvalidated = [self.makeTargetTimer isValid]; 

You can also do this in your dealloc method:

 - (void) dealloc { [_makeTargetTimer invalidate]; // Stops the timer from firing (Assumes ARC) } 

Do you scroll when you need to take an even number?

If you want the timer to NSRunLoopCommonModes while scrolling, you need to use NSRunLoopCommonModes . There is a great atonement in this matter .

  [[NSRunLoop currentRunLoop] addTimer:makeTargetTimer forMode:NSRunLoopCommonModes]; 

What is your implementation of createTargets like?

  • You put NSLog expressions in the body of this method. Are you sure it is not called?
+5
source

Source: https://habr.com/ru/post/1487611/


All Articles