31

I have an array of UIView objects. I want to call - (NSArray *)filteredArrayUsingPredicate:(NSPredicate *)predicate on this array to get array of MyCustomView objects.

How to code predicate with "isKindOf:"?

user500
  • 4,519
  • 6
  • 43
  • 56

4 Answers4

52

Try (depracated)

[NSPredicate predicateWithFormat: @"className == %@", [someObject className]]

Or

[NSPredicate predicateWithFormat: @"class == %@", [someObject class]]
Jakub
  • 13,712
  • 17
  • 82
  • 139
Jef
  • 2,134
  • 15
  • 17
  • Works with `className` too for me. Though `class` looks cleaner. – Jef Nov 09 '11 at 14:17
  • What is more appropriate? "=" or "LIKE"? – user500 Nov 09 '11 at 14:37
  • When using like, `?` and `*` can be used as wildcard characters. http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Predicates/Articles/pSyntax.html – Jef Nov 09 '11 at 15:02
  • 3
    Surely this predicate would be the equivalent of `isMemberOfClass:`, not `isKindOfClass:` as per the original question? – Tommy Feb 15 '12 at 20:41
  • I haven't tested this but you could always call `super` in the predicate and compare to that. – Jef Feb 17 '12 at 17:25
  • 3
    As @Tommy says, this is not the right answer to the question as stated. The right answer is given below by zekel. – skagedal Jul 01 '16 at 08:26
  • Right, this would be isMemberOfClass, rather than isKindOfClass. That said, I'm glad this answer is here, because using className could be the only workable solution if the class isn't actually available (e.g. cross-process calls). So thanks for that answer. – dgatwood Apr 19 '22 at 17:53
30

I got errors using Jef's method. This worked for me, though.

NSPredicate *predicate = [NSPredicate predicateWithFormat:
                                              @"self isKindOfClass: %@", class];

Source: https://stackoverflow.com/a/2556306/168594

Community
  • 1
  • 1
zekel
  • 9,227
  • 10
  • 65
  • 96
0

For anyone interested, here is the Swift version of Jef's Method:

NSPredicate(format: "className = %@", String(describing: MyCustomView.self))
-2

How about using -className as your key?

NSPredicate* foo = [NSPredicate predicateWithFormat: @"className == %@", @"MyCustomView"];
JeremyP
  • 84,577
  • 15
  • 123
  • 161