使用NSPredicate比较两个数组 [英] Comparing two arrays with NSPredicate
本文介绍了使用NSPredicate比较两个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个数组,一个表示全尺寸图像的列表,另一个表示图像的缩略图。有一种方法,使用NSPredicate,检查一个全尺寸的图像是否有缩略图?
拇指被称为img {number} _thumb.jpg,
使用数组,字符串和循环:
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(@%@没有缩略图,name);
break; //如果第一个未找到不够好删除此打破
}
}
NSLog(@%@,isSame?@所有拇指有图像:@所有拇指没有图像);
使用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);
}
}
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.
解决方案
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);
}
}
这篇关于使用NSPredicate比较两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文