我有关系的核心数据:
extension Rating {
@NSManaged var date: NSString?
@NSManaged var rating: NSNumber?
@NSManaged var ratenames: RateNames?
}
extension RateNames {
@NSManaged var name: String?
@NSManaged var rating: NSSet?
}
我需要从RateNames中选择所有值,其中所有数据都来自于所选日期的RateNames评级。
例如RateNames数据:
name=a; name=b;
例如RateNames数据:
date=10-02-2016; rating=5; linked to a
date=10-02-2016; rating=3; linked to b
date=09-02-2016; rating=2; linked to a
date=08-02-2016; rating=3; linked to a
date=08-02-2016; rating=1; linked to b
例如我需要08-02-2016
的结果
结果应该是:
{(name:a, date:08-02-2016, rating=3), (name:b, date:08-02-2016, rating=1)}
{p 1}}日期的结果应如下:
09-02-2016
我在结果中也需要b,因为我需要查看它是否为空。
我正在尝试做类似的事情:
{(name:a, date:09-02-2016, rating=2), (name:b, date:nil, rating=nil)}
但无法得到如何实现这个
答案 0 :(得分:2)
通过获取Rating
对象并使用关系获取相关name
对象的RateName
,可以更轻松地获得所需内容:
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Rating")
do {
let results = try managedContext.executeFetchRequest(fetchRequest) as! [Rating]
for result in results {
let name = result.ratenames.name
let date = result.date
let rating = result.rating
print("name:\(name), date:\(date), rating:\(rating)")
}
}
这将打印与预期结果类似的结果,但不会包含(name:b, date:nil, rating=nil)
。
<强>更新强>
如果要将上述内容限制为给定日期,可以使用谓词作为获取请求:
fetchRequest.predicate = NSPredicate(format:"date == %@", chosenDate)
但是,由于您要包含(name:b, date:nil, rating=nil)
,因此您需要获取所有RatingName
个对象。每个对象的rating
属性将包含与其相关的任何和所有Ratings
。所以我认为你需要过滤它们以确定正确的日期:
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "RateNames")
do {
let results = try managedContext.executeFetchRequest(fetchRequest)
let datePredicate = NSPredicate(format:"date == %@", chosenDate)
for result in results {
let filteredRatings = result.rating.filteredSetUsingPredicate(datePredicate)
if filteredRatings.count > 0 {
let rating = filteredRatings.anyObject()
print("name:\(result.name), date:\(rating.date), rating:\(rating.rating)")
} else {
print("name:\(result.name), date:nil, rating:nil")
}
}
}
这假设给定日期的每个Rating
只能有一个RatingName
;如果不是,你将不得不遍历filteredRatings
集。
答案 1 :(得分:0)