今天写一个苹果移动app的sample时,由于 if-else语句用得不严谨,当程序中出现bug时,影响了排查问题的效率
出问题的方法是屏幕旋转前触发的事件
-(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
在sample里,需要在屏幕旋转时改变当前的view,左旋右旋时使用另一个view
最初时代码如下
//屏幕旋转时触发的事件
-(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
//获取设备屏幕大小
CGRect devRect = [[UIScreen mainScreen] bounds];
NSUInteger viewHeight = devRect.size.height;
NSUInteger viewWidth = devRect.size.width;
//屏幕右旋时 ,使用mainLandscapeView 这个view
if (toInterfaceOrientation == UIInterfaceOrientationLandscapeRight ) {
self.view = self.mainLandscapeView; //横屏
self.view.transform = CGAffineTransformMakeRotation( deg2rad*(-90) );
self.view.bounds = CGRectMake(0.0, 0.0, viewHeight, viewWidth);
}
//屏幕左旋时 ,还是使用mainLandscapeView 这个view
else if( toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft )
{
self.view = self.mainLandscapeView; //横屏
self.view.transform = CGAffineTransformMakeRotation( deg2rad*(90) );
self.view.bounds = CGRectMake(0.0, 0.0, viewHeight,viewWidth );
}
//在其他情况下,使用mainPortraitView
else
{
self.view = self.mainPortraitView ;
self.view.transform = CGAffineTransformMakeRotation( deg2rad*(0) );
self.view.bounds = CGRectMake(0.0, 0.0, viewWidth , viewHeight);
}
[ super willAnimateRotationToInterfaceOrientation:toInterfaceOrientation duration:duration ];
}
但其实第三个else不严谨,因为存在屏向上和屏向下两种情况( 在iphone设备里只支持向上,但ipad里支持向上和向下两种情况 )
倘若在这第三个else里出现问题,将不利于定位到问题
于是将第三个else改掉,改为
//屏幕向上
else if( toInterfaceOrientation == UIInterfaceOrientationPortrait )
{
self.view = self.mainPortraitView ;
self.view.transform = CGAffineTransformMakeRotation( deg2rad*(0) );
self.view.bounds = CGRectMake(0.0, 0.0, viewWidth , viewHeight);
}
//屏幕向下
else if( toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown )
{
self.view = self.mainPortraitView ;
self.view.transform = CGAffineTransformMakeRotation( deg2rad*(-180) );
self.view.bounds = CGRectMake(0.0, 0.0, viewWidth , viewHeight);
}
//在所有正常情况之外的分支,作为异常处理分支
else
{
;
}
这样的写法类似switch……case……default, 条件分支清楚,又包含异常处理,倘若在后续的开发中需要添加新的条件分支,最后的异常处理分支 else{;}依然能发挥作用,相比之下,更改前的代码倘若再加上else分支,原先的第三个else 的执行情况就会发生变化,相当于更改了第三个else,这是开发中最不愿看到的事情。
小结一下:
写if……else时,要依照 switch……case……default 的风格来写,每一个else 都要加if 条件限制。 最后一个不加 if 的 else 用作default项。处理异常和疏漏