我想将locationManager:didUpdateHeading:
方法返回的不断更新的值存储在global int
或property int
中,以便MotionHandler类的其他函数可以使用它。但是,此委托方法似乎无法在全局存储其值,而只能在本地存储。这是为什么?是因为它不是一个真正的MotionHandler方法吗?我该如何解决这个问题?谢谢你的帮助。
MotionHandler.m
#import "MotionHandler.h"
@interface MotionHandler()
{
CLLocationManager *locationManager;
int degrees; // the global in question..
}
@end
@implementation MotionHandler
-(void) startCompassUpdates
{
locationManager =[[CLLocationManager alloc] init];
locationManager.delegate=self;
[locationManager startUpdatingHeading];
}
-(void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading
{
// This is working, a new value is stored in "degrees" & logged on the console after each update. However it only seems to be updating "degrees" locally..
degrees = (int)locationManager.heading.magneticHeading;
NSLog(@"from delegate method: %i", degrees);
}
-(int) showDegrees
{
return degrees; // This is not working. Whenever I call this method, "degrees" is always zero. Why isn't this global being updated by the previous method ?
}
TheViewController.m
//...
- (void)viewDidLoad
{
[super viewDidLoad];
currentMotionHandler = [[MotionHandler alloc] init];
[currentMotionHandler startCompassUpdates];
while(1==1)
{
NSLog(@"from showDegrees method: %i",[currentMotionHandler showDegrees]); // this just keeps returning zero..
}
}
//...
答案 0 :(得分:0)
根据OP请求,我已将我的评论转移到答案:
您需要停止使用while
循环来获得不断变化的值的反馈。由于Cocoa Touch是一个event-based system,你不能通过这种方式创建一个无限循环来劫持它的运行循环。即使在基于事件的系统之外,使用如此紧密的循环也会损害性能并且收益甚微。
如果您想要持续更新(或看似连续的事情),您可以:
我更喜欢使用计时器方法,因为它具有最低的开销,并在与UI的其余部分相同的线程中运行该方法,从而避免任何可能的线程问题。