Ios 如何使用NSExpression使用自定义函数设置NSFetchRequest属性ESTOFETCH
我在CoreData实体中有一个字符串类型的属性“message”,它存储文本,有时还包括URL。现在我需要从实体获取所有urlIos 如何使用NSExpression使用自定义函数设置NSFetchRequest属性ESTOFETCH,ios,xcode,core-data,nsfetchrequest,nsexpression,Ios,Xcode,Core Data,Nsfetchrequest,Nsexpression,我在CoreData实体中有一个字符串类型的属性“message”,它存储文本,有时还包括URL。现在我需要从实体获取所有url let predicate = NSPredicate(format:"message CONTAINS[cd] %@", "http") let fetchRequest = self.getfetchRequest(entityName: "Messages", sectionKey:nil, predicate:predicate) le
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是一个扩展字符串的自定义函数
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支持的核心数据存储中使用自定义
NSExpression
时,核心数据会尝试将表达式转换为SQL查询。这有助于提高性能,但这意味着并非所有有效的NSExpression
s都可用于核心数据
具体来说,依赖自定义函数的NSExpression
不能用于核心数据获取,因为核心数据不能将任意代码转换为SQL
您需要从fetch中删除此NSExpression
,并使用fetch的结果将其转换为URL。您也可以切换到非SQLite核心数据存储,但由于各种原因,情况通常更糟,除非您的持久存储包含非常少量的数据。请参阅-但并非所有自定义函数都与CD兼容。。