Solution for Ch 22 Bronze Challenge: Photo View Count


#1

Photorama.xcdatamodeld - Add attribute “viewCount” of type Integer 64 to Entity Photo

FlickrAPI.swift - Add attribute in func photo(fromJSON:into:)

var photo: Photo!
context.performAndWait {
  photo = Photo(context: context)
  photo.title = title
  . . .
  photo.viewCount = 0		// New statement
}

PhotoInfoViewController.swift - Add code below to the end of func viewDidLoad()

photo.viewCount += 1
store.saveContextIfNeeded()

let label = UILabel()
label.text = "\(photo.viewCount) views"
label.backgroundColor = UIColor.white
label.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(label)

label.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor).isActive = true
label.bottomAnchor.constraint(equalTo: bottomLayoutGuide.topAnchor, constant: -8).isActive = true

PhotoStore.swift - Add a new func to class PhotoStore

func saveContextIfNeeded() {
  let context = persistentContainer.viewContext
  if context.hasChanges {
    print("Save context")
    try? context.save()
  }
}

#2

You’re awesome man. I didn’t realize the hasChanges method existed


#3

I was wondering how you got xcode to recognize the new attribute viewCount for the entity Photo? I tried it and x code complains that there is no new attribute.


#4

The steps to add the new attribute viewCount to the Photo entity is just the same as those for other attributes like title, photoID.
What exact error message from Xcode do you get?


#5

I added the attribute viewCount to the core data model and made it integer64. When I set the viewCount to 0 in the flickrAPI i get the error value of type Photo has no member viewCount.


#6

According to stacksoverflow. The problem is that even though the model has a new member the managed object doesn’t. They weren’t clear on why.


#7

Open Photorama.xcdatamodeld. Select the Photo entity and open the Data Model inspector. In the Class section, locate the Codegen option and select Class Definition.

Delete the files Photo+CoreDataClass.swift and Photo+CoreDataProperties.swift in Project navigator if they exist. These files will be created and updated automatically by Xcode now.