Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iphone - how do i check if NSMutableArray ObjectAtIndex doesnt have any value

Tags:

iphone

how do i check an array if objectatIndex has any values? im using a forloop

for (i = 0; i < 6 ; i++)
{
    if ([array objectAtIndex: i] == NULL)//This doesnt work.
    {
        NSLog(@"array objectAtIndex has no data");
    }
}
like image 905
Kenneth Avatar asked Jul 15 '10 04:07

Kenneth


4 Answers

You can't store nil in a Foundation collection class such as NSArray, you have to use NSNull. To check to see if a member of the array is NSNull, you would do this:

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

If you want to see how many items are in the array, use -[NSArray count]. If you want to iterate through the array to see if any object is NSNull, but you don't care which one, you could use fast enumeration or -[NSArray containsObject:]:

for (id anObject in array) {
    if (anObject == [NSNull null]) {
        // Do something
    }
}

or

if ([array containsObject:[NSNull null]]) {
    // Do something
}
like image 144
Nick Forge Avatar answered Nov 01 '22 12:11

Nick Forge


Try using the condition

if ([[Array objectAtIndex:i] length] == 0) {
// Do what you want
}
like image 36
m177312 Avatar answered Nov 01 '22 12:11

m177312


You cannot have nil values in a NSArray (or NSMutableArray). So your if clause will never return true. Also, you should use nil instead of NULL.

like image 1
Marco Mustapic Avatar answered Nov 01 '22 14:11

Marco Mustapic


Similar to what @Marco said: you're guaranteed that objectAtIndex: will never return nil unless something goes horrifically wrong. However, by the time you get to that point, it's too late anyway and there's nothing you can do about (and you're more likely to get an exception thrown before this every happens).

If you need to store a value to indicate "there's nothing here", you should use the [NSNull null] singleton. This is exactly what it's for.

like image 1
Dave DeLong Avatar answered Nov 01 '22 13:11

Dave DeLong