2

From an array, I want to make a new mutable array holding all the items that meet a certain criteria. That's not the problem. The problem is checking if the array is empty.

   if (!theDates]) {/*do something*/}

it comes back positive regardless, because the mutable array was created. But

    if (![theDates objectAtIndex:0]) 
    {
        /* nothing got added to the array, so account for that */
    } 
    else 
    {
        /* do something with the array */
    }

It crashes.

1
  • if you've found a solution in one of the answers, don't forget to accept it in order to remove your question from the Unanswered section. Commented Aug 7, 2013 at 1:29

6 Answers 6

5

This crashes because although you have allocated your array, it's still empty. The line [theDates objectAtIndex:0] is trying to access the first object of an array, and due your array has none yet, it will crash.

To check the integrity of your array, just do this:

if (theDates.count > 0)
{
    //Do something

    id object = theDates[0]; //this for sure won't crash
}
Sign up to request clarification or add additional context in comments.

4 Comments

You don't need the 1st half of the check. Just do if (theDates.count) {
You are right. In early ages access a property of a nil pointer will cause a crash, that's no longer necessary
You don't even need the > 0 for this check. Of course it's not wrong but it's not needed either.
Yeah, that I do know. Although, I prefer to keep the > 0 in my codes, you write two more characters but you gain in legibility. It's a matter of opinion in fact, both will work
1

Use [theDates count] > 0. You're accessing a possibly non-existent element, so it will crash when it's empty.

Comments

0

Or you could use the lastObject method which will return nil if the array is empty

if (![theDates lastObject]) { do something }

Comments

0
if( (theDates!=nil) && (theDates.count > 0))
{
  //We have and existing array and something in there..
}

Comments

0

if (theDates != nil){ if (theDates.count > 0){ 'do something' } }

This should check null array then check empty array which prevents nullpointerexception arises

2 Comments

You don't need the 1st if statement. And it is standard convention to use nil, not null when dealing with Cocoa/Cocoa-touch object pointers.
Ooops, I'd forgot to switch my convention mindset from java to Obj-C, editted
0

This will work fine..

if (!URarray || !URarray.count){
  // write code here
}

Comments

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.