2016-04-21 91 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