Coltuxumab
Coltuxumab

Reputation: 787

Possible to dynamically fetch all entity relationships?

Using Xcode 9 swift 4, is it possible to dynamically fetch all relationships for an entity? I can’t seem to find any examples that can get all relationship data from an entity without hard-coding relationship names.

Edit: I miss-explained my original question, fixed above. Adding my static code, which grabs an relationship data by name rather than dynamically.

Disease is an entity with a many-many relationship own_pathology_organs to another entity Pathology_Organs.

let pathology_organs = disease.own_pathology_organs?.allObjects as! [Pathology_Organs]
for pathology_organ in pathology_organs{
    pathologyArray.append(pathology_organ.name!)
}

Upvotes: 2

Views: 208

Answers (1)

pbasdf
pbasdf

Reputation: 21536

The entity property of an NSManagedObject (or subclass) returns the NSEntityDescription for the object. The entity description provides details about the entity, including a relationshipsByName property, which returns a dictionary, the keys of which are the names of the relationships (the corresponding values being NSRelationshipDescription objects which describe the relationship). So to get a list of names of the relationships, you can use:

let relationshipNames = disease.entity.relationshipsByName.keys

From there you can use key value coding (.value(forKey:) and/or value(forKeyPath:)) to get the values from your object:

for relationshipName in relationshipNames {
    let keyPathToNameAttribute = relationshipName + ".name"
    let relatedObjects = disease.value(forKey:relationshipName)
    let relatedObjectNames = disease.value(forKeyPath:keyPathToNameAttribute)
}

Upvotes: 1

Related Questions