需求是搜索城市,跟饿了么的城市搜索相仿.
大体思路就是先判断TextField输入的字符是拼音还是汉字.然后分别用NSPredicate进行搜索.
先把获取到的城市列表对象处理一下,给他们多增加一个拼音的属性.然后根据cityName转化.
@interface ZKAreaModel : NSObject
PROP_STR province;
PROP_STR city;
PROP_STR cityPinyin;
PROP_STR district;
// 快速生成area
+ (ZKAreaModel*)generateAreaWithPro:(NSString*)procity:(NSString*)citydis:(NSString*)district;
- (NSString *)cityToPinyin;
@end
@implementation ZKAreaModel
+ (ZKAreaModel*)generateAreaWithPro:(NSString*)procity:(NSString*)citydis:(NSString*)district {
ZKAreaModel *model = [[ZKAreaModel alloc] init];
model.province= pro;
model.city= city;
model.district= district;
returnmodel;
}
- (NSString *)cityToPinyin {
return [self.city transfromToPinyin];
}
@end
- (NSString *)transfromToPinyin {
//转成了可变字符串
NSMutableString *str = [NSMutableString stringWithString:self];
CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
//再转换为不带声调的拼音
CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO);
NSString *pinYinStr = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
pinYinStr = [pinYinStrstringByReplacingOccurrencesOfString:@"\r" withString:@""];
pinYinStr = [pinYinStrstringByReplacingOccurrencesOfString:@"\n" withString:@""];
pinYinStr = [pinYinStrstringByReplacingOccurrencesOfString:@" " withString:@""];
pinYinStr = [pinYinStrlowercaseString];
returnpinYinStr;
}
由于我这个对象很多地方都用到,没有必要全部都转成拼音.所以用方法替代了.下面是TextFiled中输入字符时,用NSPredicate过滤的方法
- (void)textFieldDidChange {
NSPredicate*predicate;
NSLog(@"是否是字母:%d",[sender.textstringWithFullLetter]);
if([sender.stringWithFullChineseCharacters]) {
// 输入的全部都是汉字
NSLog(@"开始汉字搜索");
predicate = [NSPredicatepredicateWithFormat:@"city CONTAINS %@", sender.text];
}else{
NSLog(@"开始拼音搜索");
NSString*pinyin = [sender.texttransfromToPinyin];
predicate = [NSPredicatepredicateWithFormat:@"cityPinyin CONTAINS %@", pinyin];
}
NSMutableArray *resultArray = [NSMutableArray arrayWithArray:[self.citiesList filteredArrayUsingPredicate:predicate]];
}
用正则写了一个判断字符串是否都为字母
- (BOOL)stringWithFullChineseCharacters {
NSString *match = @"(^[\u4e00-\u9fa5]+$)";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
return [predicate evaluateWithObject:self];
}
但是这个方法只是粗略搜索,并不能处理多音字拼音.这个我后续会想办法优化一下.
网友评论