0

无法理解为什么这不起作用,它只是说 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];
    }
}
4

1 回答 1

1

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

如果是这种情况,ARC 将分配nilidNumberList,因此[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将始终采用分支,对对象的addObject调用nil将静默失败,这会导致您遇到的行为。

为了解决这个问题,初始化idNumberList如下:

idNumberList = [[NSMutableArray alloc] init]; 
于 2013-01-27T18:37:17.923 回答