Tim
Tim

Reputation: 129

Test if my array is nil at a given index?

I'm trying to create an NSMutableArray containing the contents of another at a given index.

I'm initializing the new array with initWithArray: if the previous array has anything at the index, otherwise with plain init

This code doesn't work but you should be able to get the idea from it:

NSMutableArray *typeCourseCutId;
if([self.typeCourseCut objectAtIndex:typeCourseIndex] != nil){
    typeCourseCutId = [[NSMutableArray alloc]initWithArray:[self.typeCourseCut objectAtIndex:typeCourseIndex]];
} else {
    typeCourseCutId = [[NSMutableArray alloc]init];
}

Is there a solution for this kind of test?

Upvotes: 2

Views: 3193

Answers (4)

Erinson
Erinson

Reputation: 88

If this can help

   if([array objectAtIndex:0] != [NSNull null])
    {
       NSLog(@"INDEX 0);
    }
    else if([array objectAtIndex:1] != [NSNull null])
    {
         NSLog(@"INDEX 1);
    }
    else if([array objectAtIndex:2] != [NSNull null])
    {
         NSLog(@"INDEX 2);
    }

Upvotes: 0

Sj.
Sj.

Reputation: 1724

You can check the count of the array. If the count is greater than the index you are fetching, then it means that an object is present at that index.

Also make sure your self.typeCourseCut is an array of NSArray objects, otherwise your initWithArray: will crash.

Also you can add an empty object to an array as [yourArray addObject:[NSNull null]]; And most importantly, without having an object at index 1, you cannot add an object to index 2.

Upvotes: 3

The Lazy Coder
The Lazy Coder

Reputation: 11838

An array should not be nil at any index. the way an array is built is that as soon as it reaches a nil object. it is considered the end of the array.

You cannot add a nil object nor can you update an existing object to nil.

If you must set something to a "Null" style object you can use NSNull in its place. THis is what most of the JSON parsers do for objects that they want to show up, but be null.

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726799

There is a special class called NSNull that is created specifically to use as null indicator in collections:

The NSNull class defines a singleton object used to represent null values in collection objects (which don’t allow nil values).

if([self.typeCourseCut objectAtIndex:typeCourseIndex] != [NSNull null]) ...

Upvotes: 6

Related Questions