Similar question have been asked before on SO. I looked into each one of them but wasn't able to find a useful answer that applies to my case so here goes. My question has two parts. But first let me explain the basics.
I have a NSManagedObject
subclass called Activity.
import Foundation
import CoreData
class Activity: NSManagedObject {
@NSManaged var endTime: NSDate
@NSManaged var id: NSNumber
@NSManaged var startTime: NSDate
@NSManaged var status: NSNumber
@NSManaged var actions: NSSet
@NSManaged var checkInAndOuts: NSSet
}
This class has two To-Many relationships (actions, checkInAndOuts) with two other classes. Below are those classes.
Action
import Foundation
import CoreData
class Action: NSManagedObject {
@NSManaged var desc: String
@NSManaged var id: NSNumber
@NSManaged var status: NSNumber
@NSManaged var name: String
@NSManaged var activity: Activity
}
CheckInAndOut
import Foundation
import CoreData
class CheckInAndOut: NSManagedObject {
@NSManaged var checkInDate: NSDate
@NSManaged var checkInUserId: NSNumber
@NSManaged var checkOutDate: NSDate
@NSManaged var checkOutUserId: NSNumber
@NSManaged var id: NSNumber
@NSManaged var activity: Activity
}
One Activity can have multiple Actions and CheckInAndOuts. In a viewDidLoad
method in a VC, I'm retrieving an array of Activities.
Now on to the issues I'm facing.
Using NSPredicate
In Action, there is a property called status
. It can have only three values; 1, 2, -1. I want to filter out actions without the status -1. When I tried to run the following predicate on the actions
property of the Activity class as described here, I got a EXC_BAD_ACCESS error.
let actionsPredicate = NSPredicate(format: "ANY actions.status != %@", -1)
How can I retrieve Activity objects which has actions with status of 1 and 2 only?
Using NSSortDescriptor
The other problem I'm facing is trying to sort the checkInAndOuts
property. This property has a set of CheckInAndOut objects. I want these objects to be sorted in ascending order by its property checkInDate
. When I ran the following line of code,
let CIAODescriptor = NSSortDescriptor(key: "checkInAndOuts.checkInDate", ascending: true)
The project crashed with the error to-many key not allowed here.
Can anyone experienced in core data please give me a helping hand? I'd really appreciate it.
Thank you.