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];
}