问题
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