我有两个实体
书 - 属性:name,desc - 关系:书籍类型为To Many to BookLang(逆:bookLang)
BookLang - 属性:nameLang,descLang,lang - 关系:bookLang,类型为To One to Book(反向:书)
在BookLang中,fr,de语言有两个对象 如果我使用
let lang = "fr"
let pre = NSPredicate(format: "book.lang == %@", lang);
Then I have to loop through the fetchResult and then loop through the book NSSet
for b in bookSet {
let lan = b.valueForKey("lang") as! String
if(lan == lang){
let name = b.valueForKey("nameLang") as! String
println(name) // the book title in french
break;
}
}
我如何才能在NSSet中找到我想要的对象
我尝试
let subPre = NSPredicate(format: "SUBQUERY(BookLang, $s, $s.lang == %@)", lang);
有错误
Unable to parse the format string "SUBQUERY(BookLang, $s, $s.lang == %@)"'
答案 0 :(得分:0)
保持简单。关系,循环,子查询 - 都是不必要的!
简单的字符串属性lang
怎么样?
let frenchBooks = allBooks.filteredSetUsingPredicate(NSPredicate(format: "lang = %@", "fr"))
或者,以真正的Swift方式
let frenchBooks = allBooks.filter() { $0.lang = "fr" }
答案 1 :(得分:-1)
为什么不使用?来创建谓词?
要获取所有符合条件的书籍,您可以对核心数据上下文使用获取请求。
let fetchRequest = NSFetchRequest(entityName: "Book") //supposing that you managed object subclass is named Book
fetchRequest.predicate = NSPredicate(format: "lang == %@", lang);
if let fetchResults = managedObjectContext!.executeFetchRequest(fetchRequest, error: nil) as? [Book] {
//DO what you want
}
这只是一个你应该完成错误和else语句的片段