Comparing two arrays with NSPredicate

安稳与你 提交于 2019-12-13 06:14:07

问题


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.


回答1:


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);
    }
}



回答2:


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:


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]]


来源:https://stackoverflow.com/questions/15743326/comparing-two-arrays-with-nspredicate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!