免责声明:您尝试使用的方法已被弃用。改为使用CMMotionManager
。然而:
设置一个委托(它应该是一个单独的类),然后使用 NSNotificationCenter 将信息分发给其他侦听器。例子:
@interface SharedAccelerometerListener: NSObject <UIAccelerometerDelegate>
@end
@implementation SharedAccelerometerListener
- (id)init
{
if ((self = [super init]))
{
[UIAccelerometer sharedAccelerometer].delegate = self;
[UIAccelerometer sharedAccelerometer].updateInterval = 0.05f;
}
}
- (void)accelerometer:(UIAccelerometer *)acc didAccelerate:(UIAcceleration *)acceleration
{
NSDictionary *info = [NSDictionary dictionaryWithObject:acceleration forKey:@"acceleration"];
[[NSNotificationCenter defaultCenter] postNotificationName:@"AccelerometerDidAccelerate" sender:nil userInfo:info];
}
@end
然后在您的侦听器类中:
id accelerationListener = [[SharedAccelerometerListener alloc] init];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didAccelerate:) name:@"AccelerometerDidAccelerate" object:nil];
- (void)didAccelerate:(NSNotification *)notif
{
UIAcceleration *acc = [[notif userInfo] objectForKey:@"acceleration"];
// do whatever you want with the acceleration
}