`
dawuafang
  • 浏览: 1106819 次
文章分类
社区版块
存档分类
最新评论

UIActionSheet buttonTitleAtIndex 方法导致程序崩溃的问题

 
阅读更多

在 UIActionSheet 的专有初始化方法中 initWithTitle 中,你可以指定每个按钮的标题,也可以用 nil 标题直接取消这个按钮:

[[UIActionSheetalloc]initWithTitle:nil

delegate:self

cancelButtonTitle:nil

destructiveButtonTitle:nil

otherButtonTitles:@"储存草稿",@"删除草稿",@"取消编辑",nil];

很显然,3 个按钮的 index 将分别为:0,1,2。

在委托方法 actionSheet: clickedButtonAtIndex: 中,你可以通过第2个参数buttonIndex 很容易获取到用户点击到的按钮的标题:

NSString* btnTitle=[actionSheetbuttonTitleAtIndex:buttonIndex];

这在 iPhone 应用程序中没有什么问题。但在 iPad 应用中很容易导致程序崩溃。这是由于iPad 的 ActionSheet 实际上是用 popover 风格显示的。我们知道 popover 一般都会提供一个“隐形”的 cancelButton按钮,这个按钮存在于 popover 之外的任何地方。只要用户触摸 popover 之外的任意区域,都等同于按下了cancelButton 按钮。

这样,在 iPad 中,上面的那个 ActionSheet 的按钮实际上有 4 个,除了 index 为 0,1,2 之外的 3 个按钮外,还有一个 index 为 -1 的“隐形”的 cancelButton 按钮。

这样,当用户触摸 popover 之外的区域时,clickedButtonAtIndex: 方法会传来一个 -1 的 buttonIndex 参数。

于是 [actionSheet buttonTitleAtIndex:buttonIndex]会立即导致一个下标越界的异常,应用程序崩溃。

因此,对于 iPad 程序,我们应当小心地检测 buttonIndex 是否在正确的范围内,clickedButtonAtIndex:方法中的语句应当修改为:

if(buttonIndex>=0and buttonIndex<=3){

btnTitle=[actionSheetbuttonTitleAtIndex:buttonIndex];
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics