Set Up Core Data and Save Company
Intermediate Training Core Data
In today's lesson we'll first look at how to setup Core Data manually ourselves. I like to do this because there aren't a lot of good tutorials online that show the correct steps for this process. Once we have everything up and running with Core Data, we can create our Company entity in the editor. Now there are some trickiness behind the auto generated files so do be careful. Finally I'll go through how to initialize the Core Data stack so that we can save and fetch companies inside of our application. This process isn't too difficult, just takes a few lines that might seem mysterious in the beginning.

Comments (19)
jaksatomovic
5 years ago
Hi Brian! It is maybe a stupid question but i have to ask. If i want to implement this way of saving and adding companies or similar i am having a problem in case if i have add button in custom tabbar controller. What would be the solution to pass data between view controllers in tabbar? I was thinking of making one delegate which pass company to customTabBarController which is subclass of UITabBarController and then when i select index 1 for example i fire another delegate which pass data to first view controller. Is this the smart way?
Brian Voong
5 years ago
jaksatomovic
5 years ago
Thanks I will try that but just in case i did misunderstood you i am trying do create company when i click button on tabbar and then when i save it i update tableview on first or second view controller ( i have 4 in tabbar) depending which was selected when i pressed add button. Company is saved but tableview not relodad because delegate = self work only in func like yours when you click navbar button and not when i put it in viewDidLoad
weare99
5 years ago
Hi Brian do you implement in this Training NSFetchResultController ? Because it handle all the annoying stuff for us ? :) Best regards from Germany
Brian Voong
5 years ago
MotivDev
5 years ago
Hi Brian! How do you handle the problem with the container taking some time to initialize? Will you be covering this case in the course? In the Apple Core Data Programming Guide they call a completion block and say to swap out your view controller after initialization completes: https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/InitializingtheCoreDataStack.html#//apple_ref/doc/uid/TP40001075-CH4-SW1 "On the other hand, you want your application to be able to access data inside of Core Data as quickly as possible, which usually means initializing Core Data as one of the first steps in the application’s life cycle. Although atypical, Core Data occasionally takes longer than usual to complete its initialization." "Therefore, it is recommended that the startup sequence of an iOS app be broken into two phases, to avoid termination:" "A minimal startup that indicates to the user that the application is launching Complete loading of the application UI after Core Data has completed its initialization" import UIKit import CoreData class DataController: NSObject { var managedObjectContext: NSManagedObjectContext init(completionClosure: @escaping () -> ()) { persistentContainer = NSPersistentContainer(name: "DataModel") persistentContainer.loadPersistentStores() { (description, error) in if let error = error { fatalError("Failed to load Core Data stack: \(error)") } completionClosure() } } } What do you recommend or what have you done in your apps to handle this issue? Thanks for sharing your knowledge with us and I'm really liking the course!! Rich
Kilian Hiestermann
5 years ago
Did huge mistake by naming my project CoreData -.-
Daniel Peach
5 years ago
I named mine CoreData as well, why is this a mistake?
dclawson
5 years ago
My guess: it's probably bad idea to name your app or any variable something that could be a reserved word in the language or any of the object properties. I'd do something like "CoreDataApp" or something similar.
Christophe Bugnon
5 years ago
Hi Brian, in FetchCompanies instead of companies.forEach({ (company) in print(company.name ?? "") }) self.companies = companies self.tableView.reloadData() I've made : companies.forEach { print($0.name ?? ""); self.companies.append($0) } self.tableView.reloadData() I think less code avoids mistakes, what do you think ?
kaldrogo
5 years ago
Hello Brian, Im having a hard time with instructions at 4:57 mark, how do execute view command to get x code to automatically create myEntity+CoreDataSwift.swift file. Thank you
lbta
5 years ago
isymfs
5 years ago
Core data is ugly
Brian Voong
5 years ago
Wiajayi
4 years ago
Hi Brain For Code data Video 10 I understand your Code logic but Swift does not recognise the code Has there been a change since you recorded?
Brian Voong
4 years ago
Wiajayi
4 years ago
Yes I review this but i still have an issue when i try to use the constant persistentContainer, after i have declared it, it does not allow me to add loadPersistentStores. It does not even appear in the autosuggestions
Brian Voong
4 years ago
Wiajayi
4 years ago
Yes
Wiajayi
4 years ago
I got around the solution by making persistentContainer into a closure similar to when you tick the core data box when starting a project. But now i am having issues with the fetch request section
Wiajayi
4 years ago
Hey Brain, realize the mistake now. should be good now
Cinquain
4 years ago
That video was fire Brian!
aldo3
4 years ago
Hi Brian, loving this series. I've seen CD usage such as --> let company = Company(context: myContext) company.name = "IBM" do{ try myContext.save() } catch...... It this style newer? I like this much better. Or is this something you go over later in the series? Thanks
Brian Voong
4 years ago
aldo3
4 years ago
Awesome. thanks
frankusu
3 years ago
Thanks for the tip aldo3!
jdhindsa
4 years ago
Hi Brian, it's a bit confusing how you had to comment out all the references to the Company struct just to get the core data save/fetch code to work. If you have several objects you need to save, is this the best approach? (ie. comment out references to the classes within your app?)
Brian Voong
4 years ago
Cinquain
4 years ago
Good stuff, this core data course is great so far
iosmkarim
3 years ago
Hi Brian, don't see any method context.save() . Is it replaced with didSave() or willSave() without throwing err?
jdhindsa
3 years ago
Is there updated source code available for iOS13? I'm running this project on XCode 11.1 and the layout is all messed up.
Brian Voong
3 years ago
jdhindsa
3 years ago
Thank you Brian! Do you have any code samples of how to use Core Data with the codable in Swift 5? I'm having a real tough time figuring it out. I came across this article, but I'm not sure if it's the right way for Swift 5? https://medium.com/@andrea.prearo/working-with-codable-and-core-data-83983e77198e
Yamak
3 years ago
Hey Brian, I am getting an error "Use of undeclared type 'Company'" when I added the entity 'Company' to the data model and also commented out the Company.swift code. As you had suggested, I look at lesson 32 for the final project for the updated code, but I also see the same error there? Any idea what needs to be go get this running?
Yamak
3 years ago
Brian, don't waste your time. It decided to work. I literally changed nothing for the past 30min. I think it waits until I send you message, then it decides to work. I've got an old 2014 macMini that takes an eternity for it to do anything.
JaimeHe
3 years ago
Hey Brian, I got some issues about adding core data stack at the beginning step. There are compiler errors show that [Use of undeclared type 'NSManagedObject',Only classes that inherit from NSObject can be declared @objc Replace '@objc(Company)' with '',Use of undeclared type 'NSFetchRequest'] and another three warning which are similar to these three errors. Have tries several times to re-integrate the core data but still does not work. I downloaded your final project that listed on lesson32 and found related comment below the video but still do not found the property solution. I am wondering that whether I have lost some key steps to complete it. If possible, may I add your wechat friends to show you the screenshot?
JaimeHe
3 years ago
I know the reason,because I named my project as "CoreData", that causes the conflict.
Tech Drawer
3 years ago
can someone tell what does "let context = persistentContainer.viewContext // context -" this line do and what is ".viewContext" Thanks
arpinoda
3 years ago
Hi Brian - is there a preferred way to check if an object already exists, before inserting? For my use case, I’m pulling JSON from an API and looping through the response models, UPSERTING them into the context (mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy). This seems fine, however I need to perform an additional operation ONLY for NEW objects - downloading an image via URL and storing/caching the data[] within the object’s attribute. With the current UPSERT technique, I’d be downloading + reading data[] for new AND existing response models, which seems a bit inefficient. Could you share any thoughts on this? Ideally I’d like to keep the data[] within an object’s attribute, rather than moving it to a 3rd party library, such as SDWebImage. Thank you for your thoughts!
Brian Voong
3 years ago
johnicode101
3 years ago
hey brian i cant seem to figure out why im not getting anything in my output, i tried searching everywhere but i cant seem to find a solution. im using xcode 11 swift 5
johnicode101
3 years ago
i keep on getting "Use of undeclared type 'Company'" on four different rows
Sanook
3 years ago
I had the same problem, I finally commented out everything in the Company.swift file and the error went away.
Matthew Easton
3 years ago
weird, i had the same problem even with everything commented except it made no difference and everything ran all the same.
Yamak
3 years ago
Hey Brian, I am not able to autocomplete or tap into the "MyEntity" at 4:50? Is there a different way to do this is the updated Xcode 11? I looked at video 32 for the completed project, but seems a lot thing have been added and moved around, that I was not able to follow. Appreciate the help!
Yamak
3 years ago
Never mind, I had to save and restart Xcode for it to realize I added a data model. Should have tried that before sending a comment through.
Brian Voong
3 years ago
HELP & SUPPORT