NSDictionary objectForKey objectAtIndex 检查是否为空

NSDictionary objectForKey objectAtIndex check if is null

我正在尝试检查我的 NSDictionary 的这个值是否为空:

if ([[dConfiguration objectForKey:@"ButtonsMenu"] objectAtIndex:count] != [NSNull null]){
    //stuff...
}

但是我收到这个错误:

Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFArray objectAtIndex:]: index (5) beyond bounds (5)'

我知道那里什么都没有,这就是我检查的原因。

感谢您的帮助。

与其说什么都没有...更多的是连 "there" 都不存在。

在尝试评估有关 objectAtIndex 的任何内容(包括它是否为空对象)之前,请检查您的 count 是否少于菜单中的对象数。

这很简单,看起来像

[dConfiguration objectForKey:@"ButtonsMenu"]

returns 一个 NSArray 或类似的东西,然后发送它 -objectAtIndex:,并提供索引 count.

错误告诉您您的数组有 5 个元素,而您要求的是第六个元素。我不确定您想检查什么以及为什么将其与 NSNull.

进行比较
0:[first] 1:[second] 2:[third] 3:[forth] 4:[fifth]

看来您只需要检查数组中是否至少有 count 个元素。

if([[dConfiguration objectForKey:@"ButtonsMenu"] count] > count)
{
    // stuff...
}

但是,请注意,这是针对集合中没有 NSNull 的情况(通常是这样)。即它只检查您的集合 在索引 count 处是否有元素 。如果你可能有 NSNulls 在那里你应该检查它是否有索引元素,如果它不是 NSNull:

NSArray *buttonsMenu = [dConfiguration objectForKey:@"ButtonsMenu"];
if([buttonsMenu count] > count)
{
     id obj = [buttonsMenu objectAtIndex:count];
     if(obj != [NSNull null]) // it's ok to compare like that
     {
        // stuff...
     }
}