iphone - 我如何检查NSMutableArray ObjectAtIndex是否没有任何值

Ken*_*eth 5 iphone

如果objectatIndex有任何值,我如何检查数组?即时通讯使用forloop

for (i = 0; i < 6 ; i++)
{
    if ([array objectAtIndex: i] == NULL)//This doesnt work.
    {
        NSLog(@"array objectAtIndex has no data");
    }
}
Run Code Online (Sandbox Code Playgroud)

Nic*_*rge 20

您不能存储nil在Foundation集合类中,例如NSArray,您必须使用NSNull.要检查是否有数组成员NSNull,您可以这样做:

for (int i = 0; i < 6; i ++) {
    if ([array objectAtIndex:i] == [NSNull null]) {
        NSLog(@"object at index %i has no data", i);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果要查看阵列中有多少项,请使用-[NSArray count].如果你想遍历数组以查看是否有任何对象NSNull,但你不关心哪一个,你可以使用快速枚举或-[NSArray containsObject:]:

for (id anObject in array) {
    if (anObject == [NSNull null]) {
        // Do something
    }
}
Run Code Online (Sandbox Code Playgroud)

要么

if ([array containsObject:[NSNull null]]) {
    // Do something
}
Run Code Online (Sandbox Code Playgroud)