4

Take the code below:

 NSPredicate *predicateSource = [NSPredicate predicateWithFormat:@"SELF = %d",5];
 NSArray *filteredArraySource = [[[self.myArray copy]autorelease] filteredArrayUsingPredicate:predicateSource];

myArray (NSMutableArray) contains 100 integers (numbers 1-100 in random order). What I'd like to do is somehow find out which index contains the number 5 without looping through each object in the array. The above code only extracts the object and places it into an array.

Any suggestions?

5
  • 1
    I think there are methods to get the index - did you check the documentation ? Commented Apr 18, 2012 at 15:45
  • I think that NSArray is a wrapper for a linear array, so with every method you can use, you will always have to scan the whole array (independently from who does it). And with 100 numers array it's not a problem sobig. Then, what if you have more than 1 item containing the number "5" , or more generically the Value "X" ? Commented Apr 18, 2012 at 15:51
  • Luckily in my case, there will never be a duplicate (each is unique). Commented Apr 18, 2012 at 15:52
  • @Kappa: You're (almost certainly) wrong. NSArray is opaque, but seems to be a front-end for a hash table: ridiculousfish.com/blog/posts/array.html Commented Apr 18, 2012 at 18:31
  • @IuliusCæsar probably not linear.. but very strange that beginning insertion graph.. seems like Std C++ vector, even worst. Anyway something like BST would be faster both in walking,searching and insertion Commented Apr 18, 2012 at 22:14

2 Answers 2

3

You can use indexOfObject:.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use indexOfObjectPassingTest:. If you need to use NSPredicate, call your predicate's evaluateWithObject: inside the block; otherwise, simply check the object's integer value to be 5.

2 Comments

I was working with an NSMutableArray and didn't think to just copy it into an NSArray. Thanks! (Will accept after "6 minutes")
@sooper You do not need to copy NSMutableArray into NSArray to make it work: whatever works for NSArray, works for NSMutableArray as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.