如何检查NSArray是否在特定索引处包含任何对象? [英] How to check if an NSArray contains any object at a particular index?

查看:33
本文介绍了如何检查NSArray是否在特定索引处包含任何对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检查 NSArray 是否在任何特定索引包含任何对象,并且在检查后我想如果对象为空,则在该特定索引处插入对象.关于如何执行此操作的任何想法?

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?

推荐答案

NSArray 不包含 nil 值; objectAtIndex:永远不会返回 nil .将 nil 添加到集合中是错误的.

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

要完成任务,可以使用占位符对象(例如 [NSNull null] )以及查询数组的 count .当然,您将需要一个 NSMutableArray 才能真正执行突变(例如,替换或插入).

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

在OS X上,您可以使用 NSPointerArray 表示包含 nil 个元素的集合.

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

使用NSNull的示例:

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

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

这篇关于如何检查NSArray是否在特定索引处包含任何对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆