我在 CoreData Entity 中有一个 String 类型的属性“消息”,它存储文本,有时包括 URL。现在我需要从实体中获取所有 url。
let predicate = NSPredicate(format:"message CONTAINS[cd] %@", "http")
let fetchRequest = self.getfetchRequest(entityName: "Messages", sectionKey:nil, predicate:predicate)
let expressionDescription = NSExpressionDescription()
expressionDescription.name = "urlFromMsg"
expressionDescription.expressionResultType = .StringAttributeType
let expression = NSExpression(forFunction: "toUrl", arguments: [NSExpression(forKeyPath: "message")])
expressionDescription.expression = expression
fetchRequest.propertiesToFetch = [expressionDescription]
fetchRequest.resultType = NSFetchRequestResultType.DictionaryResultType
这里的 toUrl 是一个扩展 String 的自定义函数。
extension String {
func toUrl()->[String]?{
let detector = try! NSDataDetector(types: NSTextCheckingType.Link.rawValue)
let matches = detector.matchesInString(self, options: [], range: NSRange(location: 0, length: self.utf16.count))
var urls = [String]()
for match in matches {
urls.append((self as NSString).substringWithRange(match.range))
}
return urls
}
}
我在这条线上崩溃了
let expression = NSExpression(forFunction: "toUrl", arguments: [NSExpression(forKeyPath: "message")])
如何在 NSExpression 中正确设置自定义方法。