gpt4 book ai didi

iphone - NSTimer 的问题

转载 作者:行者123 更新时间:2023-12-03 20:16:39 29 4
gpt4 key购买 nike

Edit2:为什么在“doSomething”方法中只更新了进度而不是point0?

编辑:使用我拥有的代码。我知道我一定忽略了一些东西,但我就是找不到它。

我正在编写一个 iPhone 应用程序,它使用 NSTimer 来执行一些任务。在程序中,我无法获取 NSTimer 循环内更新的变量的更新值。这是我的代码。

接口(interface)文件

导入

@interface TestNSTimerViewController : UIViewController {
IBOutlet UIProgressView *progress;
IBOutlet UIButton *button;
IBOutlet UILabel *lable1;
IBOutlet UILabel *lable2;
NSTimer *timer;
float point0;
}

@property (nonatomic, retain) UIProgressView *progress;
@property (nonatomic, retain) UIButton *button;
@property (nonatomic, retain) NSTimer *timer;
@property (nonatomic, retain) UILabel *lable1;
@property (nonatomic, retain) UILabel *lable2;

- (IBAction)buttonClicked:(id)sender;

@end

实现文件

#import "TestNSTimerViewController.h"

@implementation TestNSTimerViewController

@synthesize progress;
@synthesize button;
@synthesize lable1;
@synthesize lable2;
@synthesize timer;


- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}

- (void)viewDidUnload {
}

- (void)buttonClicked:(id)sender {
point0 = 1.0f;
lable1.text = [NSString stringWithFormat:@"%3.1f",point0];
timer = [NSTimer scheduledTimerWithTimeInterval:0.05
target:self selector:@selector(doSomething) userInfo:nil repeats:YES];
lable2.text = [NSString stringWithFormat:@"%3.1f",point0];
}

- (void)doSomething {
progress.progress = progress.progress+0.1;
point0 = 2.0f;
if (progress.progress == 1.0) {
[timer invalidate];
}
}
- (void)dealloc {
[button release];
[progress release];
[lable1 release];
[lable2 release];
[timer release];
[super dealloc];
}

@end

在 NSTimer 循环之后,我检查了 point0 的值。它没有将值更改为 2.3。代码有什么问题吗?

谢谢,

最佳答案

来自Reference document

Once scheduled on a run loop, the timer fires at the specified interval until it is invalidated. A non-repeating timer invalidates itself immediately after it fires. However, for a repeating timer, you must invalidate the timer object yourself by calling its invalidate method. Calling this method requests the removal of the timer from the current run loop; as a result, you should always call the invalidate method from the same thread on which the timer was installed. Invalidating the timer immediately disables it so that it no longer affects the run loop. The run loop then removes and releases the timer, either just before the invalidate method returns or at some later point. Once invalidated, timer objects cannot be reused.

您使用的计时器是重复计时器,因此您根本不应该使其无效。或者使用以下行,因为每次单击按钮时都需要触发计时器。我已将重复参数设置为“否”。

timer = [NSTimer scheduledTimerWithTimeInterval:0.05 
target:self selector:@selector(doSomething) userInfo:nil repeats:NO];

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

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