是否可以 return 只有核心数据中所需的对象
Is it possible to return only the desired objects in Core Data
我有两个实体
预订
- 属性:名称、描述
- 关系:书籍类型为 To Many 到 BookLang(反向:bookLang)
书朗
- 属性:nameLang、descLang、lang
- 关系:bookLang 类型为 To One to Book(反向: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 == %@)"'
为什么不使用就创建谓词?
要获取符合条件的所有书籍,您可以针对核心数据上下文使用提取请求。
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 语句
保持简单。关系、循环、子查询 - 都是不必要的!
一个简单的字符串属性怎么样lang
?
let frenchBooks = allBooks.filteredSetUsingPredicate(NSPredicate(format: "lang = %@", "fr"))
或者,真正的Swift时尚
let frenchBooks = allBooks.filter() { [=11=].lang = "fr" }
我有两个实体
预订 - 属性:名称、描述 - 关系:书籍类型为 To Many 到 BookLang(反向:bookLang)
书朗 - 属性:nameLang、descLang、lang - 关系:bookLang 类型为 To One to Book(反向: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 == %@)"'
为什么不使用就创建谓词?
要获取符合条件的所有书籍,您可以针对核心数据上下文使用提取请求。
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 语句
保持简单。关系、循环、子查询 - 都是不必要的!
一个简单的字符串属性怎么样lang
?
let frenchBooks = allBooks.filteredSetUsingPredicate(NSPredicate(format: "lang = %@", "fr"))
或者,真正的Swift时尚
let frenchBooks = allBooks.filter() { [=11=].lang = "fr" }