我是Objective-c的新手,并且遇到NSTimer问题。在通过开发游戏学习objective-c时,我尝试在NSTimer的帮助下使用左右按钮移动精灵。但是,因为看起来选择器没有被调用。我搜索了堆栈溢出并找到了一些解决方案,但我见过的任何解决方案都没有用。这是我的代码 -
#import "GameViewController.h"
@interface GameViewController ()
@property (strong) UIImage *playerImage;
@property (strong) UIImageView *playerView;
@property (strong) NSTimer *moveTimer;
@property CGRect playerRect;
@property int count;
@end
@implementation GameViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.count=0;
self.playerImage = [UIImage imageNamed:@"ship.png"];
self.playerView = [[UIImageView alloc] initWithImage: self.
playerImage];
self.playerRect = CGRectMake(50,400, 32,32);
self.playerView.frame = self.playerRect;
[self.view addSubview: self.playerView];
// this timer calls selector
// self.moveTimer = [NSTimer scheduledTimerWithTimeInterval:.03
// target:self
// selector:@selector(movePlayerRight:)
// userInfo:nil
// repeats:YES];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)moveLeft:(id)sender {
[self releaseTouch];
NSLog(@"Left Move");
//this timer does not call selector
self.moveTimer = [NSTimer scheduledTimerWithTimeInterval:.03
target:self
selector:@selector(movePlayerLeft:)
userInfo:nil
repeats:YES];
// [[NSRunLoop mainRunLoop] addTimer:self.moveTimer forMode:NSDefaultRunLoopMode];
// [[NSRunLoop mainRunLoop] run];
//[self.moveTimer fire];
}
- (IBAction)moveRight:(id)sender {
[self releaseTouch];
NSLog(@"Right Move");
// if(![NSThread isMainThread])
// dispatch_async(dispatch_get_main_queue(), ^{
//this timer does not call selector
self.moveTimer = [NSTimer scheduledTimerWithTimeInterval:.03
target:self
selector:@selector(movePlayerRight:)
userInfo:nil
repeats:YES];
}
- (IBAction)TouchRelease:(id)sender {
[self releaseTouch];
}
-(void) movePlayerRight:(NSTimer*)timer {
NSLog(@"Right Move Selector");
if(self.playerRect.origin.x <= 320){
self.playerRect = CGRectOffset(self.playerRect, 3, 0);
self.playerView.frame = self.playerRect;
}
}
-(void) movePlayerLeft:(NSTimer*)timer {
NSLog(@"Left Move Selector");
if(self.playerRect.origin.x >= 10){
self.playerRect = CGRectOffset(self.playerRect, -3, 0);
self.playerView.frame = self.playerRect;
}
}
-(void)releaseTouch{
if(self.moveTimer != nil){
[self.moveTimer invalidate];
self.moveTimer = nil;
}
}
@end
让我解释一下我的尝试。
然后,在一个解决方案中,我发现,线程可能会产生问题;所以,我试过 -
if(![NSThread isMainThread])
dispatch_async(dispatch_get_main_queue(), ^{
但是,线程不是这种情况,因为调试器不会进入“ dispatch_async ”行。
我做错了什么?
**解决方案:** 正如@Danil Valeev和@ aman.sood所建议的那样,取消选中Storyboard自动布局,将属性更改为'nonatomic';现在从计时器调用选择器:)
答案 0 :(得分:2)
检查movePlayerRight:或movePlayerLeft:是否被调用。并且在视图中没有使用自动布局(我认为这是原因)。您可以在“实用工具”的第一个选项卡中的xib / storyboard文件中禁用“自动布局”。
答案 1 :(得分:0)
用[NSRunLoop currentRunLoop]替换[NSRunLoop mainRunLoop]它应该可以工作