gpt4 book ai didi

iphone - 如何停止 NSTimer

转载 作者:太空狗 更新时间:2023-10-30 03:08:54 27 4
gpt4 key购买 nike

嘿,所以我只是在制作一个示例应用程序,我遇到了一点麻烦,所以我有一个 TableView ,然后我有几行,当用户单击一行时,它会将他们带到一个新 View 。在此 View 中,我有一个播放音乐的按钮。我正在使用计时器根据音乐持续时间和剩余时间增加 slider 。

现在我的问题是,我必须输入什么,以便当我通过左上角的按钮返回到 TableView 时,NSTimer 停止?

这是我目前所拥有的,我无法重复:YES 计时器停止。

#import "SecondViewController.h"

@implementation SecondViewController
@synthesize lbl1;
@synthesize timer;

-(IBAction) slide {
myMusic.currentTime = slider.value;
}

-(IBAction)play
{
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTime) userInfo:nil repeats:YES];
slider.maximumValue = [myMusic duration];
myMusic.volume = 0.2;
[myMusic prepareToPlay];
[myMusic play];
}

-(IBAction)pause
{
[myMusic pause];
}

-(IBAction)stop
{
slider.value = 0;
myMusic.currentTime = 0;
[myMusic stop];
}

- (void)updateTime{
slider.value = myMusic.currentTime;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {

//This plays music, we must give it a path to find the file and then u can change it.
NSString * pathToMusicFile = [[NSBundle mainBundle] pathForResource:@"Katy" ofType:@"mp3"];
myMusic = [[ AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:pathToMusicFile] error:NULL];
myMusic.delegate = self;
myMusic.numberOfLoops = -1;

slider.value = 0;
//[myMusic play];

[super viewDidLoad];
}


- (void)viewDidUnload {

[timer invalidate];
timer = nil;
//myMusic.currentTime = 0;
[myMusic stop];
[super viewDidUnload];

// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}

-(IBAction) TxtChange;{

lbl1.text = @" test2! I CHNAGED TEXT FROM ANOTHER XIB";
}

- (void)dealloc {
[timer invalidate];
timer = nil;
[myMusic release];
[super dealloc];
}

@end

最佳答案

使用下面的代码。它会起作用但请记住,只有当我们的计时器处于运行模式时才能调用它,否则应用程序将崩溃。

- (void)viewWillDisappear:(BOOL)animated {
//BEFORE DOING SO CHECK THAT TIMER MUST NOT BE ALREADY INVALIDATED
//Always nil your timer after invalidating so that
//it does not cause crash due to duplicate invalidate
if(timer)
{
[timer invalidate];
timer = nil;
}
[super viewWillDisappear:animated];
}

关于iphone - 如何停止 NSTimer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3509012/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com