Search code examples
swiftcore-datansmanagedobjectaccess-modifiers

Is fileprivate adequate for @NSManaged variables?


Xcode can generate this from a Core Data entity:

//  This file was automatically generated and should not be edited.

import Foundation
import CoreData

extension Media {
    @NSManaged public var imageString: String?
}

My colleague has edited it to hide the String and only expose an URL:

extension Media {
    @NSManaged fileprivate var imageString: String?
    public var image: URL? {
        return imageString != nil ? URL(string: imageString!) : nil
    }
}

Is fileprivate (or private) OK to use in that case? Is that the best practice to store an URL in Core Data?


Solution

  • That works. Whether it's a good idea depends on how you need to use the URL.

    You can just save the URL directly, without having a string property. Just make the property a "transformable" type in the Core Data model editor. Since the URL type conforms to NSCoding, Core Data will automatically convert it to/from an NSData. You would assign a URL to the property, and read URLs back later.

    That's good unless you need to fetch objects based on the URL. You can't use transformable attributes in fetch predicates, so with a transformable attribute you couldn't, for example, fetch every object with a URL that contained stackoverflow.com. If you need to do something like that, your approach is a good one. If not, the transformable attribute is simpler.