确定代码现在正在运行,但它仍然需要工作。我得到的值是“粘性的”,它们不稳定(每次我尝试返回时,磁北似乎移动了一点),我需要稍微摇动设备以刷新/唤醒值..
Game.h
#import <Foundation/Foundation.h>
#import "CoreLocation.h"
@interface Game : NSObject
<CLLocationManagerDelegate>
@property BOOL stopButtonPressed;
-(void) play;
@end
Game.m
@implementation Game
- (id) init
{
self = [super init];
self.stopButtonPressed = NO;
CLLocationManager *locationManager;
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
return self;
}
-(void) play
{
[locationManager startUpdatingHeading];
while(!self.stopButtonPressed)
{
double degrees = locationManager.heading.magneticHeading;
int degreesRounded = (int)degrees;
NSLog(@"Degrees : %i", degreesRounded);
}
}
@end
MyViewController.m
@interface MyViewController()
{
Game *game;
}
@end
@implementation MyViewController
-(void) viewDidLoad
{
game = [[Game alloc] init];
}
- (IBAction)playPressed:(UIButton *)sender
{
[game performSelectorInBackground:@selector(play) withObject:nil];
}
- (IBAction)stopPressed:(UIButton *)sender
{
game.stopButtonPressed = YES;
}
@end
我做错了什么?
答案 0 :(得分:2)
此代码将阻止该线程,如果它发生在主线程中,您将永远不会按下按钮。
CLLocationManager是一种异步机制。要正确使用它,您必须提供一个委托,当位置更新可用时它将通知(在大多数情况下,这可能是self
(其中self
是viewController或类似)。请参阅{{ 3}}
...
CLLocationManager *locationManager;
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
[locationManager startUpdatingHeading];
}
- (void)locationManager:manager didUpdateHeading:newHeading {
double degrees = newHeading.magneticHeading;
NSLog(@"Degrees : %F", degrees);
}
答案 1 :(得分:0)