2

I have an 3 NSMutableArray objects that contain CMTime objects. How can I iterate through all three of them in an efficient manner and find out if there are duplicate values in all three? For example, I'm iterating through one of time and reading the value and storing it in x. Now, I want to see if x occurs (at any position) within the other two arrays. I tried looking for a contains method, but couldn't find one. I did come across filterUsingPredicate, but I'm not sure if this is the best way of doing it nor how to actually use predicates.

2
  • Is it possible to use sets instead of arrays? Commented Oct 6, 2011 at 21:40
  • I could do, but it would mean refactoring parts of the code and, ultimately, I need to convert it back to an array to work with some third party methods which may make it inefficient. I think fluchtpunkt's method should be ok. Commented Oct 6, 2011 at 21:46

2 Answers 2

10

I tried looking for a contains method, but couldn't find one.

Use indexOfObject:

like this:

if ([array indexOfObject:object] != NSNotFound) {
    // object found
}
else {
    // object not found
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can use ([yourArray indexOfObject:x] != NSNotFound) in place of your missing contains method. However, if you're doing this quickly, often, or with a lot of elements, you should consider using NSMutableOrderedSet, which is ordered like NSMutableArray, but offers a quick and efficient contains method, as well as allowing quick operations like union and intersection, which might allow you to redesign your algorithm to iterate through your elements much less.

3 Comments

I will try the indexOf method and see if it becomes a bottleneck in performance. If so, I'll compare it with the Set and see if swapping between arrays and Sets is faster (as I need the final output to be an array so that it can be used in third party APIs).
Very wise; don't prematurely optimize. Conversion to NSArray should be fast. There's an array method that returns a proxy that reflects changes in the original, which is cool.
Thanks for the info. I'm quite new to ObjC, so finding all these methods is very helpful.

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.