Comparing two arrays with NSPredicate

2019-09-04 02:43发布

I've two array, one represents a list of full-size images and the other one represents the images' thumbnail. There is a way, using NSPredicate, to check if a full-size image has a thumbnail?

The thumb is called img{number}_thumb.jpg and the full-size image is called img{number}.jpg.

3条回答
迷人小祖宗
2楼-- · 2019-09-04 03:05

You can use indexesOfObjectsPassingTest:

NSArray *imageThumbs=   [NSArray arrayWithObjects:@"img1_thumb.jpg",@"img2_thumb.jpg",@"img3_thumb.jpg",@"img4_thumb.jpg",nil];
    NSArray *images=[NSArray arrayWithObjects: @"img1",@"img2",@"img3",@"img4",@"img5",nil];
    for(NSString *image in images)
    {
        if ([imageThumbs HasPrefix:image]) {
            NSLog(@"has thumbnail %@",image);
        }
    }  

@interface NSArray (fileterArrayUsingBlocks)
-(BOOL)HasPrefix : (NSString *)path;
@end
@implementation NSArray (fileterArrayUsingBlocks)

-(BOOL)HasPrefix : (NSString *)path
{
    NSIndexSet  *lIndexSet = [self indexesOfObjectsPassingTest:^(id obj, NSUInteger idx, BOOL *stop) {
        if ([obj hasPrefix:path]) {
            *stop = YES;  
            return YES;
        } else
            return NO;
    }];
    if (![lIndexSet count])
        return NO;
    return YES;
}

@end
查看更多
虎瘦雄心在
3楼-- · 2019-09-04 03:12

Using Arrays, strings and loop :

NSArray *thumbs=@[@"img1_thumb.jpg",@"img2_thumb.jpg",@"img3_thumb.jpg",@"img4_thumb.jpg",@"img5_thumb.jpg",];
NSArray *images=@[@"img1",@"img2",@"img3",@"img41",@"img5"];

BOOL isSame=YES;
for (NSString *name in images) {
    if (![thumbs containsObject:[NSString stringWithFormat:@"%@_thumb.jpg",name]]) {
        isSame=NO;
        NSLog(@"%@ doesn't has thumb image",name);
        break; //if first not found is not good enough remove this break
    }
}
NSLog(@"%@",isSame?@"All thumb has image":@"All thumb does not have image");

Using NSPredicate:

for (NSString *image in images) {
    NSPredicate *predicate=[NSPredicate predicateWithFormat:@"SELF like [c]%@",[NSString stringWithFormat:@"%@_thumb.jpg",image]];
    NSArray *filtered=[thumbs filteredArrayUsingPredicate:predicate];
    if (filtered.count==0) {
        NSLog(@"%@ not found",image);
    }
}
查看更多
戒情不戒烟
4楼-- · 2019-09-04 03:18

If you can arrange for both arrays to have identical values (that is, img1.jpg and img1_thumb.jpg are both represented by “1”, but in different arrays), then the set of images without thumbnails is:

[[NSMutableSet setWithArray:images] minusSet:[NSSet setWithArray:thumbnails]]
查看更多
登录 后发表回答