为什么在编码URL时格式化NSPredicate会导致swift崩溃?

时间:2015-09-07 05:56:56

标签: ios objective-c c swift nspredicate

最近,我尝试在快速项目中使用NSpredicate进行电话号码验证,但它总是崩溃。 代码是这样的:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.
    var regexPhoneNum = NSPredicate(format: "SELF MATCHES %@", "^1[0-9]{10}$")
    println(regexPhoneNum)
    return true
}

它崩溃了

var regexPhoneNum = NSPredicate(format: "SELF MATCHES %@", "^1[0-9]{10}$")

崩溃信息:

2015-09-08 09:51:17.044 PredicateTest[4319:79934] -[__NSCFString count]: unrecognized selector sent to instance 0x7c153110

我发现由使用Objective-C的NSString类别引起的崩溃,编码如下:

.h

@interface NSString (HttpManager)
- (NSString *)encode;
@end

.m

@implementation NSString (HttpManager)
- (NSString *)encode
{
NSString *outputString  = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)self,
NULL,
(CFStringRef)@"!*'();:@&=+$,/?%#[]",
kCFStringEncodingUTF8
));
outputString = [outputString stringByReplacingOccurrencesOfString:@"<null>" withString:@""];
return outputString;
}
@end

任何能够解决这个问题的人或者给我一些建议,谢谢!

1 个答案:

答案 0 :(得分:0)

得到它!可能NSPredicate格式化字符串默认使用编码方法!该类别的编码与系统的冲突... omg,朋友们要小心这种情况。我只需通过添加前缀来更改方法名称并解决问题!!!