Why is T.entity() returning zeroes in init()?

Hi,


I am trying to develop a generic way to populate UITabeViewDataSource. It is largely working, but I had a print statement in the init() and it was causing a crash. It was printing entityName, a computed property, coded thusly:


public class RecordArray<T: NSManagedObject> {
   
   
    var entityName: String {
        let entity = T.entity()
        return entity.name!
    }
  


When I step through it, entity is all zeroes, like a classical objective-c nil, even though entity() is a non-optional function. But in later functions it works.


Does anyone know the reason for this?


---

Mark

Replies

I’ve seen this sort of thing when properties do not have their nullability set correctly. In this case

entity
is declared as never being nil, but it sounds like it is. Alas, the documentation doesn’t shed any light on why this might happen. I recommend two things:
  1. Confirm that this is, in fact, the problem. You can do this by adding an Objective-C category that declares a a new property,

    maybeEntity
    perhaps, that is optional. Then have the Objective-C method implementation just return the
    entity
    property. At that point your Swift code can access
    maybeEntity
    and determine if it is indeed nil.
  2. Once you’ve confirmed the problem, you might ask over in App Frameworks > Core Data to see if anyone can input as to why it might be happening.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"