How to check if an NSArray contains any object at

2019-08-08 17:00发布

问题:

I am trying to check an NSArray if it contains any object at any particular index and upon checking it i want to insert the object at that particular index if it is empty. Any idea on how to do this?

回答1:

NSArray does not contain nil values; objectAtIndex: will never return nil. it is an error to add nil to the collection.

To accomplish your task, you could use a placeholder object such as [NSNull null] as well as querying the array's count. Of course, you will need an NSMutableArray to actually perform mutations (e.g. replace or insert).

On OS X, you could use NSPointerArray to represent a collection which contains nil elements.


Example using NSNull:

const NSUInteger idx = ...;
NSMutableArray * array = ...;

if ([NSNull null] == [array objectAtIndex:idx]) {
  [array replaceObjectAtIndex:idx withObject:someObject];
}