Search code examples
objective-ccocoansarray

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?


Solution

  • 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.