Chapter 22 Silver Challenge

I have a question about optionals and Core Data. When I did the Silver Challenge and added the attribute “views” to the Photo entity, I assumed that I would have to treat it as an optional and unwrap it the first time I used it, because I didn’t see obvious place to initialize it. For my trouble I got an error message that said something about Int64, optionals and NSManaged quantities. Not being able to either initialize it or unwrap it, I finally got frustrated and just used it and it worked fine. My problem is that I don’t have a clue why it works.

When I added the number of views attribute to the data model (as an Int64) and regenerated the NSManagedObject subclass, it was not flagged as optional like the other items. Not sure why, but I figured XCode knew what it was doing & just went with it.

When I opened the Data Model Inspector & looked at the Int64 attribute I added, the Default box was checked and a default value of 0 was specified; none of the other attributes had the Default box checked. I thought maybe this was why it was not an optional in the generated file, but when I unchecked Default & regenerated the NSManagedObjects subclass again, it was still not an optional. So I have no idea what makes this different from the other attributes.

According to this, it’s due to a limitation in Objective-C. Since Objective-C didn’t have optionals, you can’t have optionals for scalar attributes like integers or floats, you can only have them for things that would be classes in Objective-C. I assume that because Objective-C could use a nil pointer to represent an object with no value, Core Data can represent a Swift optional with no value that way.

Thanks for the research, it helps. The same must be true for a Bool. I noticed it did not flag as optional when I did the chapter 23 challenge.