Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive CoreData attributes

I have a potentially stupid question about a potentially stupid database design.

Say I have this design (in an iOS project using CoreData):

Class A
- name: NSString
- children: NSSet of Class A objects
- parent: Class A object

so it's a simple parent/child setup. This is all fine.

Now, I want to make it so that if a Class A object doesn't define a value for 'name', its parents are searched until one is found that does define 'name' and this value is returned.

This is a tricky thing to do, because my natural reaction was to override the getter for name like this:

- (NSString *)name
{
  return name =! nil ? name : self.parent.name;
}

but this doesn't work because 'name' has to be accessed via self.name because this is a CoreData entity.

Then I had the idea of making a new method called nameRecursive which works like:

- (NSString *)nameRecursive
{
  return self.name =! nil ? self.name : self.parent.name;
}

but this feels very clunky and not very elegant (as the real life version of Class A has many properties which need to work like this), but I haven't been able to think up anything nicer.

Does anyone have any thoughts on a) whether or not this is a stupid design or b) how I might solve it in an elegant way.

Any ideas or thoughts would be brilliant. Thanks in advance.

like image 300
Mason Avatar asked Nov 29 '25 15:11

Mason


1 Answers

It looks like the following question may help you implement the first method you mention

How can I override a getter on a property when using Core Data?

So instead of doing

return name =! nil ? name : self.parent.name;

You could do something like...

return [self primitiveValueForKey:@"name"] =! nil ?
                     [self primitiveValueForKey:@"name"] : self.parent.name;

Update to answer the query in the comments

Apple recommends you do not do this. See the 'Custom Attribute and To-One Relationship Accessor Methods' section of the Apple documentation for Managed Object Accessor Methods. That provides more detail of how to do this properly (and encourages you not to.) Maybe if you have many properties that work in exactly the same way you could make a method such as

recursiveValueFor: (NSString*) property;

which can act as a generic wrapper around the recursion logic while not interfering with CoreData dynamic properties

like image 168
Dolbz Avatar answered Dec 01 '25 05:12

Dolbz