[英]NSMutable Array
我有一個NSMutableArray:
NSMutableArray *temp = //get list from somewhere.
現在有一個方法objectAtIndex,它以指定的索引返回對象。
我想做的是,我首先要檢查指定索引處的對象是否存在。 如果存在,那么我想獲取該對象。 就像是:
if ([temp objectAtIndex:2] != nil)
{
//fetch the object
}
但是我在if語句中說該索引超出范圍時出現異常。
請任何人告訴我如何實現這一目標。
您在NSArray中不能有“空”插槽。 如果[myArray count] == 2,即array有兩個元素,則可以確定在索引0有一個對象,在索引1有一個對象。情況總是如此。
首先使用計數方法檢查長度。
if ([temp count] > indexIWantToFetch)
id object = [temp objectAtIndex:indexIWantToFetch];
您可以這樣做:
初始化時,請執行以下操作:
NSMutableArray *YourObjectArray = [[NSMutableArray alloc] init];
for(int index = 0; index < desiredLength; index++)
{
[YourObjectArray addObject:[NSNull null]];
}
然后,當您要添加但檢查它是否已經存在時,請執行以下操作:
YourObject *object = [YourObjectArray objectAtIndex:index];
if ((NSNull *) object == [NSNull null])
{
/// TODO get your object here..
[YourObjectArray replaceObjectAtIndex:index withObject:object];
}
只需檢查索引是否> = 0和<count
返回接收器中當前對象的數量。
- (NSUInteger)count
int arrayEntryCount = [temp count];
首先,您檢查數組的長度-
NSMutableArray * temp = //從某處獲取列表。
現在檢查-如果(臨時長度){
您的對象類* obj = [temp objectAtIndex:indexnumber];
// indexnumber是0,1,2,3或任何人...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.