如何查找数组是否包含对象(不使用for循环)?

Nar*_*ana 1 iphone objective-c nsarray ios

我使用下面的代码检查ary_navigationControllerViews数组包含myclass对象或不工作正常,但我需要for for循环.我知道我们有像containsObject这样的方法但在这种情况下如何使用.有没有办法检查这个条件没有使用for循环.

NSArray *ary_navigationControllerViews = [[NSArray alloc] initWithArray:[self.navigationController viewControllers]];
    for(id obj_viewController in ary_navigationControllerViews) {
        if([obj_viewController isKindOfClass:[myClass  class]]) {
            //some my code
            return;
        }
    }
Run Code Online (Sandbox Code Playgroud)

Emp*_*ack 12

NSPredicate使这种工作变得更加简单.

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY SELF.class.description == %@", [[myClass class] description]];
BOOL exists =  [predicate evaluateWithObject:ary_navigationControllerViews];
if (exists) {
    //some my code
    return;
}
Run Code Online (Sandbox Code Playgroud)

要获取视图控制器实例,可以使用以下代码.

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self.class.description == %@", [[self class] description]];
NSArray *vcs = [ary_navigationControllerViews filteredArrayUsingPredicate:predicate];
if ([vcs count] > 0) {
    id vc = [vcs objectAtIndex:0];
    // Now vc is the view controller you are looking for
}
Run Code Online (Sandbox Code Playgroud)