如果NSString尚未被提交,则将NSString添加到NSMutableArray - 不起作用

时间:2013-01-26 18:52:35

标签: nsstring nsmutablearray nsarray

无法理解为什么这不起作用,它只是说每次都没有使用过id num ......并且从不将它添加到数组中。任何有关这方面的帮助将非常感激。我几乎肯定错过了一些明显的东西,但它让我很生气。

- (IBAction)idNumInputEnd:(id)sender
{
    // Check if ID Number has been used before, if it hasnt, add it to the list.
    NSString *idNumCheck = idNumberInput.text;

    if ([idNumberList containsObject:idNumCheck])
    {
        NSLog(@"This id number has been used before, ask user if he would like to reload the       data");
    }
    else
    {
        NSLog(@"This id number hasn't been used before and is thus being added to the array");
        [idNumberList addObject:idNumCheck];
    }
}

1 个答案:

答案 0 :(得分:1)

我怀疑(由Martin分享,根据他的评论)idNumberList从未被分配并初始化为空NSMutableArray

如果是这种情况,ARC会将nil分配给idNumberList,因此[idNumberList containsObject:idNumCheck]会评估为nil,以及[idNumberList addObject:idNumCheck]

换句话说,您评估的代码就像

if (nil) {
    NSLog(@"This id number has been used before, ask user if he would like to reload the       data");
} else {
    NSLog(@"This id number hasn't been used before and is thus being added to the array");
    nil;
}

鉴于此,将始终使用else分支,addObjectnil对象的调用将无声地失败,这会导致您遇到的行为。

要解决此问题,请按以下方式初始化idNumberList

idNumberList = [[NSMutableArray alloc] init];