how do i check an array if obje开发者_如何学CctatIndex 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.
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.
精彩评论