我正在尝试实现一个计时器,但我的访问权限很差......我没有在dealloc中使用release。
.h
NSTimer *_timerAnimacao;
@property (nonatomic, retain) NSTimer *timerAnimacao;
.m
@synthesize timerAnimacao = _timerAnimacao;
这是我打电话给计时器的地方。
if(acondition)
_timerAnimacao = [NSTimer scheduledTimerWithTimeInterval:0.06 target:self selector:@selector(changeTimeFilter:) userInfo:nil repeats:YES];
else
_timerAnimacao = [NSTimer scheduledTimerWithTimeInterval:0.06 target:self selector:@selector(changeTimeFilterHide:) userInfo:nil repeats:YES];
changeTimeFilter
工作正常......但changeTimeFilterHide
正在 BAD Access 。
-(void)changeTimeFilter:(NSTimer *)theTimer{
if (tAnimacaoFilter<5) {
[_tbFilters setFrame:CGRectMake(_tbFilters.frame.origin.x, _tbFilters.frame.origin.y, _tbFilters.frame.size.width, 58*tAnimacaoFilter)];
}
if(tAnimacaoFilter < 10) {
tAnimacaoFilter++;
[_tbFeeds setFrame:CGRectMake(_tbFeeds.frame.origin.x, _tbFeeds.frame.origin.y + (4.4*tAnimacaoFilter), _tbFeeds.frame.size.width, _tbFeeds.frame.size.height - (4.4*tAnimacaoFilter))];
[imgBordaTbDireita setFrame:CGRectMake(imgBordaTbDireita.frame.origin.x, _tbFeeds.frame.origin.y - 4, imgBordaTbDireita.frame.size.width, imgBordaTbDireita.frame.size.height)];
[imgBordaTbEsquerda setFrame:CGRectMake(imgBordaTbEsquerda.frame.origin.x, _tbFeeds.frame.origin.y, imgBordaTbEsquerda.frame.size.width, imgBordaTbEsquerda.frame.size.height)];
}
else {
if(_timerAnimacao)
[_timerAnimacao invalidate];
[btnFilter setEnabled:YES];
}
}
-(void)changeTimeFilterHide:(NSTimer *)theTimer{
if (tAnimacaoFilter<5) {
[_tbFilters setFrame:CGRectMake(_tbFilters.frame.origin.x, _tbFilters.frame.origin.y, _tbFilters.frame.size.width, (58*5) - (58*tAnimacaoFilter))];
}
if(tAnimacaoFilter < 10) {
tAnimacaoFilter++;
[_tbFeeds setFrame:CGRectMake(_tbFeeds.frame.origin.x, _tbFeeds.frame.origin.y - (4.4*tAnimacaoFilter), _tbFeeds.frame.size.width, _tbFeeds.frame.size.height + (4.4*tAnimacaoFilter))];
[imgBordaTbDireita setFrame:CGRectMake(imgBordaTbDireita.frame.origin.x, _tbFeeds.frame.origin.y - 4, imgBordaTbDireita.frame.size.width, imgBordaTbDireita.frame.size.height)];
[imgBordaTbEsquerda setFrame:CGRectMake(imgBordaTbEsquerda.frame.origin.x, _tbFeeds.frame.origin.y, imgBordaTbEsquerda.frame.size.width, imgBordaTbEsquerda.frame.size.height)];
}
else {
if(_timerAnimacao)
[_timerAnimacao invalidate];
[btnFilter setEnabled:YES];
}
}
答案 0 :(得分:2)
对invalidate需要做的是将NSTimer设置为nil,如下所示:
[_timerAnimacao invalidate];
_timerAnimacao = nil;
如果你不这样做,你的下一个命令将无法正常工作,例如:
if(_timerAnimacao)
[_timerAnimacao invalidate];
请注意:if(_timerAnimacao)
与if(_timerAnimacao == nil)
相同!
同时看看这个:How do I use NSTimer?
答案 1 :(得分:0)
当你启动和无效时,NSTimer的实例需要在内存中。
您可以通过两种方式实现这一目标:
将NSTimer设置为Appdelegate类的属性,并在需要的地方使用它。
NSTimer * timer = [(MyAppDelegate *)[[UIApplication sharedApplication] delegate] .timer;
创建一个新类并将NStimer设置为属性。创建一个类方法以返回该类的单例实例。
static MyClass * obj = NULL;
(MyClass *)实例 { @synchronized(个体经营) { if(obj == NULL) obj = [[self alloc] init]; }
返回(OBJ); }
我更喜欢第二种方法。