Reputation: 211
I have an arra which contains be 5 values. But I know at least on one index the value will be NULL. I've tried something like this
if ([array objectAtIndex:2]!=nil) //Right now array contains 5 values in total
{
//do something
}
But it doesn't seem to work as I know that at index 2 there is no value but still goes INTO the "if" Statement.
Upvotes: 2
Views: 2428
Reputation: 727137
Your code should work. Checking != nil
is unnecessary, and you can use array index operator, so you can write
if (array[2]) {
...
}
If the code goes into the conditional, there is an object at array[2]
. Add NSLog
call to see what's there:
if (array[2]) {
NSLog(@"Element 2 is '%@'", array[2]);
// ... The rest of your code
}
I get
Element 2 is "
output
Then it's an empty string. Use
if ([array[2] length]) {
...
}
to check for it.
Upvotes: 4
Reputation: 2805
You can use this code to check object exist at index
if ([array objectAtIndex:2])
{
//object Exist
}
else
{
//Object not Exist
}
Upvotes: 0