Search code examples
swiftcore-dataswift2nsfetchrequest

Excluding a property/field from fetching - Core Data


How do you exclude a field from fetching? For example I have 3 Fields:

  1. username : String?

  2. password : String?

  3. capturedImages : NSSet? of Images // I want to exclude this from fetching

I want to exclude capturedImages because it may contain huge amount images. If I just want to fetch the username and password, How should I do that?


Solution

  • Since capturedImages is a relationship, those entities will not be prefetched (by default), but exist as part of a fault in your object graph.

    Your images will not be retrieved until you specifically access the set's items.

    On an unrelated note, you can modify your NSManagedObject subclass as follows, to make it easier to work with the object in Swift.

    • Don't define an attribute as optional, if it is not optional in the model.
    • Use the Swift Set type in place of NSSet.
    • Strongly type the contents of a set.

      @NSManaged var username: String
      @NSManaged var password: String
      @NSManaged var capturedImages: Set<Image>
      

    This eliminates unnecessary unwrapping or casting, as well as allowing Swift to type-check your code before it is compiled.