TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SOLVED: CoreData best practice -- relationships or new FetchRequest?

Forums > SwiftUI

Hi,

Is there a best practice for CoreData describing whether one should use the relatipnships vs. when to use a new FetchRequest? In my subviews I'm passing an object that has a relationship to the entity I need, but I'm unclear about the efficiency of this?

For example, if I have an object with a 1-n relationship: Action (1-n) Logs .. if I want to access the logs from an action, I can do this: self.action.logRelationship ... or, I can pass the actionId and fetch a brand new set of logs dynamically.

Any thoughts?

3      

hi Pete,

the better strategy is to access the Logs for an Action using action.logRelationship; these give you direct access, without the need to put out a fetch request (which would be like asking to find the logs you already have).

you probably know, but for anyone who does not know this, the logRelationship will either be typed as an NSSet? or an NSOrderedSet?, for which you'll need a little conversion. so consider using one of these to get a real, Swift type:

extension Action {

// if logRelationship is unordered, the default, as an NSSet?
//
  var logs: [Log] { 
        if let logs = logRelationship as? Set<Log> {
            return logs.sorted(by: { $0.name < $1.name }) // your choice on how to sort
        }
          return []
   }

// or if logRelationship is ordered, as an NSOrderedSet?
//
  var logs: [Log]  {
      if let logs = logRelationship?.array as? [Log] {
        return logs
     }
     return []
  }

}

hope that helps,

DMG

3      

Agree with DMG. Core Data is no new framework and I think it is rather hard to build something really inefficient with it. Especially if you are not handling large amounts of data. Generally if you can avoid FetchRequest then do so.

If you are using generated entity classes, you can modify them and toss out NSSet and instead use Set with the correct entity specified as a generic parameter.

3      

@pcampbell83 , Probably not the answer your looking for, but I think it's probably "it depends". Is perfomance an issue or is it memory overhead? Try it both ways then measure it in instruments. If you If you don't like the results of traversing the relationship, try solving it with a fetch. The older Core Data Programming guide (https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CoreData/Performance.html#//apple_ref/doc/uid/TP40001075-CH25-SW1) addresses some of these issues in the performance section. From your question, you could probably do this with prefetching the entities for the relationship, that way they are already loaded and prevents a fault from firing. Doing it this way does increase memory overhead a little bit, but prevents another round trip to the persistent store.

Also, tryin using the SQLDebug in your Scheme > Run > Arguments > Arguments Pass on Launch. This will help see how your fetches are performing. -com.apple.CoreData.SQLDebug 1

I don't think there's a one answer that would be a "best practice". You'll just have to measure it and see which one you think is best for your particular situation.

3      

Thanks all -- I'm not optimising for a problem per se (and I'm not trying to mico-optimise, I assure you!), I'm just trying to follow the practice that would be considered best for most as I'm fairly new to Swift and very much new to CoreData. I'm happy to let CoreData do it's thing, as you're right, it's a far older framework than I had first thought.

It makes sense to me to use the relationship that I defined in the model; and I've just been extending the base class as noted to return the array instead of the Set<> .. but, I had forgotten about ordering :) so @delawarematguy reminded me to include that, too.

3      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.