我在CoreData Entity中具有String类型的属性“message”,该属性存储文本,有时还包括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中正确设置自定义方法。
最佳答案
在提取请求和SQLite支持的Core Data存储中使用自定义NSExpression
时,Core Data会尝试将表达式转换为SQL查询。这有助于提高性能,但是这意味着并非所有有效的NSExpression
都可以与Core Data一起使用。
具体来说,依赖于自定义函数的NSExpression
不能与Core Data fetch一起使用,因为Core Data无法将任意代码转换为SQL。
您需要从获取中删除此NSExpression
并使用获取的结果转换为URL。您也可以切换到非SQLite Core Data存储,但是由于各种原因,这通常会更糟,除非您的持久性存储包含非常少量的数据。
关于ios - 如何使用NSExpression使用自定义函数设置NSFetchRequest propertiesToFetch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38911231/