Edit2:为什么在"doSomething“方法中只更新了进度,而没有更新point0?
编辑:使用我的代码。我知道我必须忽略一些东西,但我就是找不到。
我正在编写一个iphone应用程序,它使用NSTimer来执行一些任务。在程序中,我无法获得在NSTimer循环中更新的变量的更新值。这是我的密码。
接口文件
导入
@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。密码怎么了?
谢谢,
发布于 2010-08-25 06:43:25
来自参考文件
一旦安排在运行循环中,计时器就会在指定的时间间隔内触发,直到它失效为止。不重复的计时器在触发后立即失效。但是,对于重复计时器,您必须通过调用timer对象的失效方法,亲自使其失效。调用此方法请求从当前运行循环中删除计时器;因此,您应该始终从安装计时器的同一线程调用失效方法。使计时器无效立即禁用它,使其不再影响run循环。然后,run循环移除并释放计时器,要么在失效方法返回之前,要么在稍后的某个点。一旦失效,定时器对象就不能被重用。
您使用的计时器是一个重复的计时器,因此您根本不应该使它失效。或者使用下面的行,因为每次单击按钮时,定时器都需要启动。我已将重复参数设置为否。
timer = [NSTimer scheduledTimerWithTimeInterval:0.05
target:self selector:@selector(doSomething) userInfo:nil repeats:NO];发布于 2010-08-25 09:44:52
- (void)buttonClicked:(id)sender {
point0 = 1.0f;
lable1.text = [NSString stringWithFormat:@"%3.1f",point0];
[self.timer invalidate];
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.05
target:self selector:@selector(doSomething) userInfo:nil repeats:NO];
lable2.text = [NSString stringWithFormat:@"%3.1f",point0];}
然后在doSometing函数中:
- (void)doSomething {
progress.progress = progress.progress+0.1;
point0 = 2.0f;
if (progress.progress < 1.0) {
[self.timer invalidate];
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.05
target:self selector:@selector(doSomething) userInfo:nil repeats:NO];
}
}我认为你应该在某个时候重新设置进度变量。
发布于 2010-08-26 02:45:03
我找到了答案。标签2.在NSTimer完成run循环之前执行文本行。我需要重写我的代码,以便它等待直到NSTimer完成运行循环。
https://stackoverflow.com/questions/3563065
复制相似问题