Solution for Ch 22 Bronze Challenge: Photo View Count

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()
  }
}
1 Like

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

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.

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?

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.

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.

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.

That worked out. Thanks you’ve helped a lot.

I’m getting another error at compile time I don’t know what the problem is. If you could help me I’d be greatful. The error is: Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1

Stacks said that means a file is missing