2

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.

0

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Seeing your reputation I know you can't be wrong. But it's not working either :(
@Rahul It looks like your element is an empty string then.
Then how am I supposed to check it then?
@Rahul If your array contains only NSStrings, then the condition if ([array[2] length]) should work.
I am sure you are a busy man. But coz of you it finally worked :). Thank you so damn much for your time . Was trying it from last 45 mins :D
0

You can use this code to check object exist at index

if ([array objectAtIndex:2]) 
{
   //object Exist
}
else
{

  //Object not Exist
}

6 Comments

It's not working. Still going into the "if" statement.
then there is some string my be "null" exist you can print that value in log and check whether it is nil or a string "null"
I have use this code NSString *str=nil; NSLog(@"String %@",str); and out is "String (null)" and you are saying nothing exist how is it possible?
Because you are using NSString and I am using NSArray
then You can use this string.length>0 then exist otherwise not
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.