0

好的,代码现在可以工作了,但它仍然需要工作。我得到的值是“粘性的”,它们不稳定(每次我尝试返回时,磁北似乎都会移动一点),我需要稍微摇晃设备以刷新/唤醒价值观..

游戏.h

#import <Foundation/Foundation.h>

#import "CoreLocation.h"

@interface Game : NSObject

<CLLocationManagerDelegate>

@property BOOL stopButtonPressed;

-(void) play;

@end

游戏.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

我的视图控制器.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

我究竟做错了什么?

4

2 回答 2

2

此代码将阻塞线程,如果它发生在主线程中,您将永远无法按下按钮。

CLLocationManager 是一种异步机制。要正确使用它,您必须提供一个委托,它将在位置更新可用时通知它(这self在大多数情况下可能是(在哪里self是 viewController 或类似的)。请参阅CLLocationManagerDelegate 文档

...
    CLLocationManager *locationManager;
    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    [locationManager startUpdatingHeading];
}

- (void)locationManager:manager didUpdateHeading:newHeading {
    double degrees = newHeading.magneticHeading;
     NSLog(@"Degrees : %F", degrees);
}
于 2012-07-30T14:14:07.507 回答