use*_*210 6 cocoa-touch objective-c nstimer ios
我一直试图通过使用一个计时器来显示我的应用程序的左下角NSTimer,并使"经过时间"显示UILabel在左下角,但它并没有为我工作.
-(void)viewDidLoad
{
NSTimer *aTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(aTime) userInfo:nil repeats:YES];
}
-(void)aTime
{
NSLog(@"....Update Function Called....");
static int i = 1;
Label.text = [NSString stringWithFormat:@"%d",i];
i++;
}
Run Code Online (Sandbox Code Playgroud)
计时器实际上工作,但我不能让它由按钮触发.我正在尝试让计时器继续运行,而不是在进入下一个storyboard/xib文件时重新启动.
Mid*_* MP 11
要在按下按钮时实现计时器操作,您需要在以下IBAction方法上编写它:
- (IBAction) buttonPress
{
NSTimer *aTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(aTime) userInfo:nil repeats:YES];
}
Run Code Online (Sandbox Code Playgroud)
要存储以前的值,可以使用NSUserDefaultsSQLite数据库.为此,我建议NSUserDefaults.
更改aTime方法,如:
-(void)aTime
{
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
id obj = [standardUserDefaults objectForKey:@"TimerValue"];
int i = 0;
if(obj != nil)
{
i = [obj intValue];
}
Label.text = [NSString stringWithFormat:@"%d",i];
i++;
[standardUserDefaults setObject:[NSNumber numberWithInt:i] forKey:@"TimerValue"];
[standardUserDefaults synchronize];
}
Run Code Online (Sandbox Code Playgroud)
我认为问题在于该方法aTime位于您的视图控制器中,当您进入另一个视图时,该视图控制器被释放,您无法再执行选择器aTime。
所以我建议您将aTime方法和放置i到单例(或进入另一个视图时不会释放的任何对象)并将单例设置为计时器的目标。
您还应该将下面的代码保留在视图控制器中,以便您在返回此视图时可以正确更新标签。
-(void)viewDidLoad
{
NSTimer *aTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(aTime) userInfo:nil repeats:YES];
}
-(void)aTime
{
NSLog(@"....Update Function Called....");
Label.text = [NSString stringWithFormat:@"%d",theSingleton.i];
}
Run Code Online (Sandbox Code Playgroud)
更好的选择:
你可以将 i 声明为你的单例的属性,然后向 i 添加一个观察者,然后你的标签就会按时更新。当你想计算时间时调用 -startTimer 。
单例:
@interface Singleton
@property (nonatomic,retain) NSNumber *i;
@end
@implementation
+(Singleton*)instance
{
//the singleton code here
}
-(void)startTimer
{
NSTimer *aTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(aTime) userInfo:nil repeats:YES];
}
-(void)aTime
{
NSInteger temp = [i integerValue];
temp ++;
self.i = [NSNumber numberWithInteger:temp];
}
Run Code Online (Sandbox Code Playgroud)
视图控制器:
-(void)viewDidLoad
{
[super viewDidLoad];
[[Singleton instance] addObserver:self forKeyPath:@"i" options:NSKeyValueObservingOptionNew context:NULL]];
}
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
{
NSLog(@"....Update Function Called....");
Label.text = [NSString stringWithFormat:@"%@",[Singleton instance].i];
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
38082 次 |
| 最近记录: |