【发布时间】:2023-03-21 15:54:01
【问题描述】:
我正在使用一个 UIView 子类,该子类具有一些 CAAnimation,该子类将在另一个类的 performegue 之后执行。在 UIView 类中,我使用 CADisplayLink 和 NSTimer 来增加动画中使用的 CATextLayer。无论何时,我在运行动画后回到之前的视图控制器,它一直在后台运行。当我转到正在播放动画的视图控制器时,它显示的计数不正确。我的代码有什么问题吗?
在.h文件中,
@property (assign,nonatomic) CFTimeInterval duration;
@property (nonatomic,strong) NSTimer *tim1;
@property (nonatomic,strong) NSTimer *tim2;
@property (nonatomic,strong) NSTimer *tim3;
@property (nonatomic,strong) NSTimer *startup;
@property (nonatomic,strong) NSTimer *starter;
@property (nonatomic,strong) NSTimer *suspender;
@property (nonatomic,strong) NSTimer *humansum;
@property (nonatomic,strong) NSTimer *transportsum;
@property (nonatomic,strong) NSTimer *wastesum;
@property (nonatomic,strong) NSTimer *watersum;
@property (nonatomic,strong) NSTimer *energysum;
@property (nonatomic,strong) NSTimer *humanslowsum;
@property (nonatomic,strong) NSTimer *transportslowsum;
@property (nonatomic,strong) NSTimer *wasteslowsum;
@property (nonatomic,strong) NSTimer *waterslowsum;
@property (nonatomic,strong) NSTimer *energyslowsum;
@property (nonatomic,strong) CADisplayLink *displayLink;
在 .m 文件中, //下面的代码是在方法内部调用的
displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(tick:)];
[displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
- (void)tick:(CADisplayLink *)sender
{
duration = sender.duration;
startup=[NSTimer scheduledTimerWithTimeInterval:(2+(0.05*duration)) target:self selector:@selector(calltheanimating_function) userInfo:nil repeats:NO];
if(initil==YES){
//
humansum =[NSTimer scheduledTimerWithTimeInterval:(15.4+(0.05*duration)) target:self selector:@selector(sum1) userInfo:nil repeats:YES];
}
else{
humansum =[NSTimer scheduledTimerWithTimeInterval:13.4 target:self selector:@selector(sum1) userInfo:nil repeats:YES];
}
在 sum1 方法中,
-(void)sum1{
NSLog(@"Hvalue %f",humanvalue);
num11=humanvalue;//
CATextLayer *humanscore=self.layers[@"humanscore"];
humanscore.string=@"0";
actualtext=0;
tmep=0;
humanslowsum =[NSTimer scheduledTimerWithTimeInterval:(0.7/(0.7*num11)) target:self selector:@selector(final1) userInfo:nil repeats:YES];
}
为了实现缓出功能,我使用了要求中提到的 75% 的快速增量和 25% 的慢速增量。
-(void)final1{
if(tmep<round(num11)){
tmep++;
CATextLayer *t=self.layers[@"stepscore"];
int m=[t.string intValue];
m++;
t.string=[NSString stringWithFormat:@"%d",m];
CATextLayer *humanscore=self.layers[@"humanscore"];
actualtext++;
humanscore.string=[NSString stringWithFormat:@"%d",actualtext];
NSLog(@"%d",m);
}
else{
[humanslowsum invalidate];
}
}
即使我使计时器无效,此计时器仍会继续运行,从 dealloc() 方法中的超级视图中删除视图。请帮我解决这个问题。
【问题讨论】:
-
你确定会调用 dealloc 吗?它有一个保留周期,因为视图保留了计时器,而计时器保留了视图。
-
是的,我正在使 dealloc 中的所有计时器无效,并且我检查了调试模式并调用了该方法
-
你还能打印humanlowsum的值吗?似乎它正在被替换,但之前的值并未失效。这可能会为该变量创建多个计时器。
-
我得到了在中间停止的值,如果我回到上一个视图,那么它会不断增加并在控制台中打印。我不知道为什么:(
标签: objective-c uiview nstimer cadisplaylink