2016-04-21 121 views
0

我已经写了下面的断言,但它崩溃下来的应用程序,原因是'Unable to parse the format string "(rootActivityId IN 12,13 AND (activityType == 3 OR activityType == 2)) OR (activityId IN 12,13 AND (activityType == 3 OR activityType == 2))"'NSPredicate:无法解析格式字符串

let activityTypeClause = "(activityType == \(NSNumber(integer: ActivityType.TypeTwo)) OR activityType == \(NSNumber(integer: ActivityType.TypeOne)))" 
fetchRequest.predicate = NSPredicate(format: "(rootActivityId IN \(activityIds) AND \(activityTypeClause)) OR (activityId IN \(activityIds) AND \(activityTypeClause))") 

// activityIds contains coma separated string 

我无法揣摩出我做错了。

回答

5

从在文档:

Equivalent to an SQL IN operation, the left-hand side must appear in the collection specified by the right-hand side. For example, name IN { 'Ben', 'Melissa', 'Nick' }. The collection may be an array, a set, or a dictionary—in the case of a dictionary, its values are used.

这表明逗号分隔的字符串实际上应该是一个集合对象。它是否需要是一个NS风格的Swift风格的集合,我不清楚。

不评论它是否可以作为一个谓语,但下面不给我解析错误:

let rootActivityId = "12" 
let activityIds = ["12", "13"] 

let pred = NSPredicate(format: "rootActivityId IN %@", argumentArray: [activityIds]) 
+0

由于'NSPredicate'几乎是肯定还是Objective-C的可能是笔者的需求,遗憾的是,至使用谓词打算的printf样式格式来构建他的谓词。没有字符串插值。然后Swift集合到Objective-C集合映射应该可以工作。这是我在阅读本文时的反应,已经是正确的答案。 – Tommy