0

I have a CoreData Entity named List it has a Relationship to an Entity Address. This is a one-to-many relationship seeing as an Address can be only be one List.

Address entities have an Attribute flag which is an Integer 16.

Is there a way for me to define a Fetched Property in the List entity with a count of all related Address entities that have their flag set to 1? What would the predicate look like?

Thanks

Joseph
  • 9,171
  • 8
  • 41
  • 67

1 Answers1

0

Yes, you can do it like this:

Create a fetch request for the List entity and set its predicate to:

[NSPredicate predicateWithFormat:@"address.flag == %@", @1]

Also don't forget to prefetch relationship so you don't encounter any cache misses.

Razvan
  • 4,122
  • 2
  • 26
  • 44
  • yes, I know it is possible with a fetch request. I was wondering if I could have it as a fetch property, so that I wouldn't have to constantly call up the requests and instead just call an `attribute` of the entity `List`. – Joseph Jun 06 '15 at 11:29
  • As far as I'm aware, you can't access a Managed Object and/or its relationship(s) without a fetch. But you can fetch only the attributes you're interested in. If that's the case, tell me and I'll edit my answer. – Razvan Jun 06 '15 at 11:33
  • I'm aware of fetching only single attributes. What I was looking for something that would make something like the following possible: `myList.countAllFlagged` and get a NSNumber of all `addresses` in `list` that have `flag` set to `1`. I guess I'll have to stick with my fetchRequest. – Joseph Jun 06 '15 at 11:40
  • Another way you could do what you want would be to create an Integer attribute in your `List` entity named `count` or whatever and increment it every time you add a new address to that `List`. You could do this in a convenience method in a category of your `List` Managed Object. – Razvan Jun 06 '15 at 11:40
  • thought of that one too, was just too "scared" of possible race-conditions on asynchronous-tasks. Also though about adding a custom method to my `mogenerator` generated `NSObjects` that performs the fetch for me, so that I can keep my code cleaner. – Joseph Jun 06 '15 at 11:42
  • I think that something like this could also work: `int addressCount = [[ list valueForKeyPath:@"address.@count"] intValue]` or even better call the `count` method on your `Address` relationship attribute set but you must first filter/extract the values you're interested in. Check NSSet and NSCountedSet classes. – Razvan Jun 06 '15 at 11:49