ios NSArray 索引处的对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11225433/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 18:59:24  来源:igfitidea点击:

Object at index in NSArray

iphoneiosarrays

提问by hgpl

I have an array. I want to check whether there is an object present in a particular index or not. How to do this? Please help.

我有一个数组。我想检查特定索引中是否存在对象。这该怎么做?请帮忙。

回答by Pfitz

if you just want to check if there is an object

如果你只是想检查是否有对象

if (myIndex < [array count])

if you want to find a specific object

如果你想找到一个特定的对象

[array indexOfObject:myObject];

if you want to know if the object at some index is of some class

如果你想知道某个索引处的对象是否属于某个类

[[array objectAtIndex:myIndex] isKindOfClass:[TheClassToCompareTo class]];

回答by onegray

BOOL exists = index < [array count] ? YES : NO;

BOOL exists = index < [array count] ? YES : NO;

回答by Maulik

You can use containsObjectmethod to check weather your array contains the specific object or not. If contains, then get its index by indexOfObjectmethod

您可以使用containsObject方法来检查您的数组是否包含特定对象。如果包含,则通过indexOfObject方法获取其索引

if ([yourArrayArray containsObject:yourObject]) 
{
    NSLog(@"Found");
    int index = [yourArray indexOfObject:yourObject];     
}

回答by anoop4real

I know this is old thread but just trying to help.

我知道这是旧线程,但只是想提供帮助。

You can add a category to NSArraysomething like this

您可以向NSArray这样的内容添加类别

@implementation NSArray (Safe)

- (id)safeObjectAtIndex:(NSUInteger)index {
    if (index >= [self count]) return nil;
    return [self objectAtIndex:index];
}

@end

回答by Parag Bafna

Use indexOfObject:method.

使用indexOfObject:方法。

if ([Array indexOfObject:object]==index) {
        //code
    }

回答by trojanfoe

You should check the length of the array (using the countmethod) and given NSArraycannot contain nilit must therefore contain something:

您应该检查数组的长度(使用该count方法)并且给定NSArray不能包含nil它因此必须包含某些内容

- (BOOL)arrayContainsSomethingAtIndex:(NSUInteger) index
{
    return [_myArray count] > index;
}

回答by Bruno Ferreira

First you must check if the index of that object is smaller than the size of the array, then you query the array at that index.

首先,您必须检查该对象的索引是否小于数组的大小,然后在该索引处查询数组。

if (index < [array count] && [array objetAtIndex:index]){
/* Your code*/
}

回答by Sumanth

check like this

像这样检查

if([array objectAtIndex:i]!= nil)
{
NSLog("Object present");
}
else{
NSLog("Object Not Present")
}

Modified: You should make like this

修改:你应该像这样

if(i<=[array count]){
    if([array objectAtIndex:i]!= nil)
    {
    NSLog("Object present");
    }
    else{
    NSLog("Object Not Present")
    }
}

This will not raise exception and object in array should compare with nil value

这不会引发异常,数组中的对象应该与 nil 值进行比较