Tim Vermeulen
Tim Vermeulen

Reputation: 12562

NSFetchedResultsController performFetch function decodes all objects

I'm very new to working with Core Data, so I'm probably doing something wrong.

I'm using NSFetchedResultsController with UITableView, and the performFetch() function decodes all objects in the corresponding entity. However, I only want to decode a single of those in the prepareForSegue function, rather than to decode all of them right when the view is loaded, because decoding my custom object takes a while.

How would I fix it? Should I perhaps create an extra entity to contain the information I don't need to draw the table cells but only need in the next view, or would a one-to-one relationship be appropriate here?

Upvotes: 0

Views: 71

Answers (1)

Tom Harrington
Tom Harrington

Reputation: 70946

It sounds like this attribute is a Core Data "transformable" attribute, so that Core Data automatically invokes NSCoding methods when loading and saving data.

What you're seeing is normal for that design. When you fetch a managed object, it's a "fault" object with no property values. But as soon as you access any attribute values, all of them are loaded, including transformables. If that's a problem (and I second @Wain's suggestion of using Instruments to verify this before making changes based on assumptions), you have some options for dealing with it. In no particular order these include:

  • Make the attribute "binary" instead of "transformable", and then add your own code to invoke NSCoding methods only when you actually need them. Both attribute types mean that the value is stored as a binary blob, the only difference is whether you call NSCoding methods or you let Core Data do it for you. With this change, you'd still load all of the attribute's data into memory, but you wouldn't run through the init(coder:) method until/unless you decide it's necessary.
  • Use propertiesToFetch on the fetch request, along with setting requestType to NSDictionaryResultType. This would let you just not fetch this attribute, however it would give you NSDictionary objects instead of NSManagedObject (or your subclass).
  • Move this attribute's data into a separate, related entity. Core Data fault firing loads the object's attribute values but not its related objects. So, you could fetch whatever entity you're fetching but not have any data to encode/decode until you decide to traverse the relationship.

Each of these would require some refactoring of code, with varying levels of convenience.

Upvotes: 1

Related Questions