@twostraws is just demonstrating a technique here.
Of course creating a new country for each candy bar you add is redundant. You don't need to have Switzerland in your database six or seven times. Once you create ONE Switzerland record, you should use this for any and all candy bars that originated in Suisse! This is why he discusses the one-to-many relationship.
So why then? WHY does he create several UK origin entities in the video.
He is doing this to demonstrate a feature of CoreData that actually PREVENTS you from creating duplicate country entities.
Go back to 2:37 in the video. At this point, @twostraws if asking you to ADD a constraint to the Countries entity. You are asked to add shortName
to the contraints container and save your model. This constraint tells CoreData that no matter how many times you try to create a country with the shortName
of "UK", CoreData is instructed to only save it once, and ignore all other attempts.
So your question is valid. You ask:
How do you check to see if Origin already exists?
This is a GREAT question. It shows you're looking to reduce inefficiencies in your code! Nice!
Off the top of my head, I might consider a function in a Countries extention. You would provide the function with a country shortName
. The code would create a fetch request and return the full name, if found. Otherwise, it might return nil.
If it returns a nil, this means the country shortName (and its full name) are not in CoreData. This might clue you in that you should create one.
Update:
Last night, with visions of sugar plums dancing in my head, I remembered a lecture from another great Swift professor named Paul
. If you're not aware, please use the Google and seek knowledge of CS193p
. Paul Hegarty teaches a semester course in Swift development at Stanford University. Lecture 12 is about CoreData. In this lecture @39:20 he starts writing a function to find an airport code in Core Data. If the code is found, fine! Otherwise, the function creates a new airport code. Perhaps this will help update your solution?
CS193p: Lecture 12: Core Data
Please return and let everyone know how you solved this! We want you to share what you've learned!