Getting Index of an Object from NSArray?

后端 未结 7 1469
没有蜡笔的小新
没有蜡笔的小新 2020-12-12 23:17

i am trying to get index of an array through indexOfObject method as follows but when i try to log the value to test the index i get a garbage value.. for t

相关标签:
7条回答
  • 2020-12-13 00:01
    NSNumber *num1 = [NSNumber numberWithInt:56];
        NSNumber *num2 = [NSNumber numberWithInt:57];
        NSNumber *num3 = [NSNumber numberWithInt:58];
        NSMutableArray *myArray = [NSMutableArray arrayWithObjects:num1,num2,num3,nil];
        NSNumber *num=[NSNumber numberWithInteger:58];
    
        NSInteger Aindex=[myArray indexOfObject:num];
    
        NSLog(@" %d",Aindex);
    

    Its giving the correct output, may be u have done something wrong with storing objects in ur array.

    0 讨论(0)
  • 2020-12-13 00:01

    Try this:

    NSArray's indexOfObject: method. Such as the following:

    NSUInteger fooIndex = [someArray indexOfObject: someObject];
    
    0 讨论(0)
  • 2020-12-13 00:03

    I just checked. Its working fine for me. Check if your array has the particular number. It will return such garbage values if element is not present.

    0 讨论(0)
  • 2020-12-13 00:07

    The index returned by indexOfObject will be the first index for an occurence of your object. Equality is tested using isEqual method.
    The garbage value you get is probably equal to NSNotFound.
    Try testing anIndex against it. The number you are looking for isn't probably in your array :

    NSNumber *num=[NSNumber numberWithInteger:56];
    NSInteger anIndex=[myArray indexOfObject:num];
    if(NSNotFound == anIndex) {
        NSLog(@"not found");
    }
    

    or log the content of the array to be sure :

    NSLog(@"%@", myArray);
    
    0 讨论(0)
  • 2020-12-13 00:09

    If you're using Swift and optionals make sure they are unwrapped. You cannot search the index of objects that are optionals.

    0 讨论(0)
  • 2020-12-13 00:10

    indexOfObject methord will get the index of the corresponding string in that array if the string is like @"Test" and you find like @"TEST" Now this will retun an index like a long number

    0 讨论(0)
提交回复
热议问题