首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NSArray - objectAtIndex:

NSArray - objectAtIndex:
EN

Stack Overflow用户
提问于 2011-05-30 02:59:44
回答 3查看 3.2K关注 0票数 1

我有个问题。如果objectAtIndex:x为空,我会得到一个错误。在我的代码中,用户必须插入一个由"/“分隔的代码,例如32/31/43甚至32//12。一切正常,但是如果用户插入一个没有"/”的单个数字,我会得到图片中显示的错误,但我希望得到一个警告视图,告诉用户代码插入的格式错误。我希望这是清楚的。谢谢

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-05-30 03:06:13

也许最好的方法是在创建数组后检查它,以确保有3个值。

代码语言:javascript
复制
NSArray *componentDepthString = [depthString componentsSeperatedByString:@"/"];
if ([componentDepthString count] == 3) {
    // everything is good and you can continue with your code;
    //  rest of the code;
} else {
    // the user input bad values or not enough values;
    UIAlertView *myAlert = [[UIAlertView alloc] 
                                    initWithTitle:@"can't continue"
                                    message:@"user input bad values"
                                    delegate:self
                                    cancelButtonTitle:@"Cancel"
                                    otherButtonTitles:nil];
    [myAlert show];
    [myAlert release];
}

编辑:您必须编辑标题和消息,以表明您想要什么,但这是关于如何在错误发生前检查错误数据以及如何显示警告的基本思想。你将不得不添加你自己的逻辑如何处理它与用户

票数 2
EN

Stack Overflow用户

发布于 2011-05-30 03:08:15

您可以使用以下命令测试数组中的组件数量

代码语言:javascript
复制
[componentDepthString count]

在盲目地查看数组之前,请确保数组中包含的元素与您所需的一样多:

代码语言:javascript
复制
// probably a bad idea to name the array with the word "string in it
NSArray *componentDepths = [depthString componentsSeparatedByString:@"/"];
NSInteger numComponents = [componentDepths count];

if(numComponents < 3) {
    // show an alert...

    return;
}

// otherwise proceed as before
票数 2
EN

Stack Overflow用户

发布于 2011-05-30 03:12:34

对于字符串"2“,componentsSeparatedByString将返回一个只有一个对象的数组:字符串"2”。

您正在尝试读取索引为1的对象(即第二个对象),但该数组只有一个对象。尝试从NSArray末尾以外的位置读取值是错误的。

看起来你想要做的是要求输入的值有两个‘/’,所以为什么不先检查一下呢?

代码语言:javascript
复制
if ([componentDepthString count] != 3) {
   // show an alert and return
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6169760

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档