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");
}
}
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
}
Try using the condition
if ([[Array objectAtIndex:i] length] == 0) {
// Do what you want
}
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With