我开发了一个有两个UIButton的iOS应用程序,但是当我按下它们时按钮似乎有些滞后。有时滞后非常糟糕(有时需要10秒)。我几乎肯定它与我正在使用的NSTimer有关。我只是想让它按下按钮后立即切换UIViewControllers,我不希望有任何延迟。这是我的代码:
RealTimeModeViewController.m
#import "RealTimeModeViewController.h"
@interface RealTimeModeViewController ()
@end
@implementation RealTimeModeViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(UpdateTime:)
userInfo:nil
repeats:YES];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (void)UpdateTime:(id)sender
{
// This is where I do everything in my app
}
@end
ViewController.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(UpdateTime:)
userInfo:nil
repeats:YES];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (void)UpdateTime:(id)sender
{
// Most of code goes here
}
@end
两个UIButton通过Modal样式相互连接ViewController。也许我应该把按钮放在主线程中?我对线程不太熟悉。谢谢。
答案 0 :(得分:0)
如果我不得不猜测,你正在使用UpdateTime:
方法做一些耗时的事情。因为它在主线程上并且每1秒运行一次,所以你可能正在放慢其他一切。 UIButton事件在主线程上,所以很可能是因为你在主线程上做了所有事情,它被“阻塞”了。
对于不准确但不会挂起主线程的计时器实现,请参阅以下答案:https://stackoverflow.com/a/8304825/3708242
如果您必须具有NSTimer实施的一致性,请尝试减少UpdateTime:
所做的事情。
答案 1 :(得分:0)
我以前遇到过这个问题。您应该使用UIActivityIndicatorView
按钮延迟可能是由UpdateTime
方法引起的。在UIActivityIndicatorView
的{{1}}中使用ViewWillAppear
,然后执行ViewDidLoad
方法。
这就是我的意思:
UpdateTime
则...
-(void) ViewDidLoad
{
UIActivityIndicatorView *act = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
[act setFrame:CGRectMake(320/2-50, 130, 100, 100)];
act.layer.cornerRadius = 10;
[act.layer setBackgroundColor:[[UIColor colorWithWhite: 0.0 alpha:0.30] CGColor]];
UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(0, 80, act.frame.size.width, 20)];
[lable setText:[NSString stringWithFormat:@"%@", string]];
[lable setFont:[UIFont fontWithName:@"Helvetica-Light" size:12.0f]];
[lable setTextAlignment:NSTextAlignmentCenter];
[lable setTextColor:[UIColor whiteColor]];
[act addSubview:lable];
[self.view addSubview: act];
[act startAnimating];
// perform the method here, and set your delay time..
[self performSelector:@selector(UpdateTime:) withObject:nil afterDelay:1.0];
}
评论并告诉我这是否有帮助:)