我正在编写一个检查设备初始物理位置的应用程序。如果它是平的,则设备应该做一些事情,然后用户应该将设备定位在其他位置,以便应用程序可以做额外的工作。如果应用程序不是平的,那么用户应该定位该位置使其变平,然后继续按照应用程序的要求将设备移动到不同的位置。
无论设备最初是否是平的,或者如果用户必须移动设备以使其变平,这两个动作都应该调用相同的方法,从而导致一系列需要处理的 if/else 语句。以下是检查设备初始物理方向的方法:
- (void) accelerometerCheck {
UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
if (orientation == UIDeviceOrientationFaceUp || orientation == UIDeviceOrientationFaceDown) {
currentTest++;
[self orientationChanged:nil];
}
else {
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(orientationChanged:)
name:UIDeviceOrientationDidChangeNotification
object:[UIDevice currentDevice]];
}
}
currentTest 是一组枚举,每次设备的方向改变时,其值都必须改变。每次设备改变位置时,都会执行一次新的测试,总共进行三个测试(平面、横向和纵向测试)。上述代码块调用的方法如下所示:
- (void) orientationChanged:(NSNotification *)note {
if (note == nil) {
device = [UIDevice currentDevice];
}
else
device = note.object;
由于某种原因,我的代码没有达到下面的“if”语句
if(currentTest == flatTest) {
if (device.orientation == UIDeviceOrientationFaceUp || device.orientation == UIDeviceOrientationFaceDown) {
//do something
}
else {
//do something other stuff
}
}
// If the device is initially in the flat position, then it should
// call the method "orientationChanged" and come directly to this
// point in the method...which it is not doing.
else if (currentTest == landscapeTest) {
if (device.orientation == UIDeviceOrientationLandscapeLeft || device.orientation == UIDeviceOrientationLandscapeRight) {
//do some tests
}
else {
}
currentTest++;
}
else if (currentTest == portraitTest) {
if (device.orientation == UIDeviceOrientationPortrait || device.orientation == UIDeviceOrientationPortraitUpsideDown) {
//do more tests
}
else {
return;
}
currentTest++;
}
else if(currentTest == doneTest) {
//give test results to the user
}
else
[self testFail];
}
else if(currentTest == timeoutTest) {
//Do something to tell the user the test timed out
}
}
谁能看到我做错了什么?我的感觉是,我要么没有将 NSNotification 参数的正确值传递给方法“orientationChanged”,要么由于某种原因,我无法将orientationChanged 方法中的前两个 if/else 语句连接到 if/else 语句来吧。