In a project I am working on, we have multiple persistent stores and fetched properties are defined on the Entities to provide access to the objects that live in the different stores.
When I run Editor
-> Create NSManagedObject Subclass
, the fetched properties do not get populated in the subclass, and therefore are not accessible in the different controllers that use this Entity.
My curiosity is how to define these objects in the subclass so that they can be used.
For example imagine I have some object below called "Some Object", and this object has a fetched property on it called "imageFile" (The File object lives in a different store so cannot be referenced directly)
class SomeObject: NSManagedObject {
@NSManaged var name: String
@NSManaged var id: String
@NSManaged var imageID: String
@NSManaged var imageFile: File //Not generated automatically like the rest
}
Unfortunately the above attempt fails with the following error:
unrecognized selector sent to instance 0x60800865de50
So my question is a nutshell, is how do you access Fetched Properties, or what is the syntax to reference them.
Please no answers saying "Don't use Fetched Properties" or "Use only one persistent store". I already know how to use normal relationships and want to know how to utilize this feature of Core Data. Thanks in advance!
UPDATE
Trying some of the solution's posted below I ran into some interesting information that may help. I printed out the object using "po someObject" and was suprised to see the following in the output under the data attribute:
imageFile = "<relationship fault: 0x618000043930 'imageFile'>";
imageID = "some Id"
However when trying to access imageFile using someObject.imageFile I am unable to access it. Using the valueForKey["imageID"] I am able to get a reference, but it fails on the cast to File every time. When printing the object out I get:
Optional(Relationship fault for (<NSFetchedPropertyDescription: 0x6180000e1780>), name imageFile, isOptional 1, isTransient 1, entity SomeObject...
Final Update
the valueForKey["imageID"]
will trigger the fault and fetch the property, I had the attributes flipped in my xcdatamodelid
file, and thats why it wasn't finding it at first.
In Objective-C you could define a @dynamic
property file in a
category on SomeObject
, but something similar does not exist in Swift
(as far as I know).
So the only possibility is to use Key-Value coding to retrieve the fetched property (which is always represented as an array):
if let files = yourObject.valueForKey("imageFile") as? [File] {
// ...
}
Of course you can wrap this into a computed property as suggested in @gutenmorgenuhu's answer.