【问题标题】:Add NSString to NSMutableArray if NSString is not already pressent - not working如果 NSString 尚未存在,则将 NSString 添加到 NSMutableArray - 不工作
【发布时间】:2013-01-26 18:52:35
【问题描述】:

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

【问题讨论】:

  • 你确定你的方法被调用了吗?尝试在其中放置一个断点。知道idNumCheckidNumberList 的值也会很有趣
  • 可能idNumberList从未被分配+初始化。

标签: nsstring nsmutablearray nsarray


【解决方案1】:

我怀疑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 分支将始终被采用,对nil 对象的addObject 调用将静默失败,这会导致您遇到的行为。

要解决这个问题,请初始化 idNumberList,如下所示:

idNumberList = [[NSMutableArray alloc] init]; 

【讨论】:

  • 很抱歉回复延迟。按照您的建议初始化 idNumberList 效果很好。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-26
  • 1970-01-01
  • 1970-01-01
  • 2012-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多