关于iphone:-[UIThreePartButton text]:无法识别的选择器

-[UIThreePartButton text]: unrecognized selector

我已经为此苦苦挣扎了一段时间,但无法弄清楚。

这是一个为页面添加书签的操作表(对于类似 safari 的应用程序)当我点击 Okay 时,我得到了
-[UIThreePartButton 文本]:实例 XXXX

处无法识别的选择器

我似乎无法理解我的痛苦所在。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0)
    {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Bookmarks" message:@"Please enter the site name: \
 \
 \
" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok", nil];
        alert.center=CGPointMake(160, 50);
        alert.tag=1;

        UITextField *siteName=[[UITextField alloc]initWithFrame:CGRectMake(20, 70, 245, 30)];
        siteName.backgroundColor=[UIColor clearColor];
        siteName.borderStyle=UITextBorderStyleRoundedRect;
        siteName.autocorrectionType=UITextAutocorrectionTypeNo;
        siteName.delegate=self;
        siteName.clearButtonMode=UITextFieldViewModeWhileEditing;
        siteName.text=[[mainDelegate.sitesArray objectAtIndex:tag] objectForKey:@"webSite"];
        siteName.returnKeyType=UIReturnKeyDone;
        siteName.tag=2;
        [alert addSubview:siteName];

        [alert show];
    }
}

我意识到它在它下面的警报视图方法上死了:

1
2
3
4
5
if(alertView.tag==1)
    if (buttonIndex==1)
    {
        if(((UITextField*)[alertView.subviews objectAtIndex:4]).text==@""||((UITextField*)[alertView.subviews objectAtIndex:4]).text==nil)
        {

特别是在 if(((UITextField*)[alertView.subviews objectAtIndex:4])

我在该操作表上有 4 个按钮/操作,其余的都可以使用...


不要尝试手动遍历 Apple 未记录的 UI 元素的视图层次结构。做类似 [alertView.subviews objectAtIndex:4] 的事情是危险的,因为你最终不得不对 UIAlertView 的内部结构做出盲目的假设。

在这种情况下,您点击了错误的元素(UIThreePartButton)并导致您的应用程序因异常而崩溃。即使您现在确实获得了正确的文本字段位置的索引,也不能保证 Apple 不会在未来的操作系统版本中更改视图编号或顺序,从而突然导致您的应用程序的所有安装崩溃。

为防止这种情况,请保留对 UITextField 的引用,这样您就无需在 UIAlertView 上探查视图层次结构。

更好的是,不要使用警报视图进行文本输入,而是使用自定义模式视图。确实应该为不常见的错误显示或其他关键更新保留警报。来自 iOS 人机界面指南:

The infrequency with which alerts
appear helps users take them
seriously. Be sure to minimize the
number of alerts your app displays and
ensure that each one offers critical
information and useful choices.

作为一个仅供参考,您还泄漏了上述代码中的 siteName UITextField,可能还有您的 UIAlertView。


如果每个操作有 4 个按钮,您的 objectAtIndex 会不会是 3 而不是 4?似乎您遇到了越界异常。

具体而言,如果数组中有 4 个项目,则 objectAtIndex:4 将生成异常,因为最后一个有效索引是 3.