tags:

views:

60

answers:

4

hi guys, 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");
        }

}

+1  A: 

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.

Marco Mustapic
oh i see. no wonder im getting errors . thanks!
Kenneth
`nil` and `NULL` are the same thing. *By convention* we use `nil` for object pointers and `NULL` for everything else, but it's just convention. There is no difference between the two. (You can verify this by cmd-double clicking on a `nil` and seeing what it's defined as)
Dave DeLong
yeah, you are right
Marco Mustapic
+1  A: 

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.

Dave DeLong
alright got it!
Kenneth
+4  A: 

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
}
Nick Forge
ok! thanks for the info! useful codes i could use.
Kenneth
+1  A: 

As far I know- There is no index without an object. because when you remove an object, the array will trimmed by itself. You can put some empty object like @"" or NSNull, but that an object at least.

Another point, you will get NSRangeException if the index you are looking for is out of bound.

Sadat
oh i see. thanks for the info!
Kenneth