4
votes

I am using Swift in Core Data generated subclass of NSManagedObject. There is a transient optional property title.(The optional is not Swift's optional, but Core Data's optional.) So I need a custom getter. My code is

class ShoppingList: NSManagedObject {

    @NSManaged var title: String

    func title() -> String {
        return "something"
    }
}

The Objective-C version of the getter works fine. However, Xcode tells me that "the func title() is an invalid redeclaration". I tried to use computed property, but get that "@Managed property can not use computed property".

So my question is, is there an alternative way to get custom accessors(getters) in Swift version of NSManagedObject subclassing?

1

1 Answers

0
votes

You could use a different name for a computed property, and have it return the title variable.

@NSManaged var title: String

var myTitle : String {
   return self.title
}

Would that work for you? Apple does it like this in many places by naming the actual var with an underscore in front, and the computed property with the same name but without the underscore