So, here's my issue:
The local path for realms on iOS are located in the Documents Directory. I can open them with:
let realm = try! Realm()
Opening a sync realm is different as they are located by URLs
https://realm.io/docs/swift/latest/#realms
I have a UICollectionView with a Results<Object> I can render default data to called in the AppDelegate from a separate file by writing to the Realm on launch
Separate File
class SetUpData {
// MARK: - Seed Realm
static func defaults() {
let realm = try! Realm()
guard realm.isEmpty else { return }
try! realm.write {
realm.add(List.self())
}
}
}
App Delegate
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// MARK: - Set Up Realm If Deleted
var config = Realm.Configuration()
config.deleteRealmIfMigrationNeeded = true
Realm.Configuration.defaultConfiguration = config
SetUpData.defaults()
return true
}
From here, client-side (iOS), I am able to successfully log in (rolled my own log in but the values correspond to the Realm Object Server (ROS) admin user) and retrieve the default values from List.cell and begin writing "Lists" to my application.
However, when I configure my realm with a Sync Configuration par opening a synchronized Realm requires a User that’s been authenticated to the Object Server and that’s authorized to open that Realm, I reasonably crash in my cellForItemAtIndexPath return lists.count fatal error: unexpectedly found nil while unwrapping an Optional value because there is no initial data to return.
That makes sense. But what do I do?
Do I need to create a Realm file in the default config and migrate it to the server? I attempted to change my config to a Sync object in the App Delegate with the code below (which is what I am using in ListViewController). No dice.
private func setUpRealm() {
let username = "\(LoginViewController().username.text!)"
let password = "\(LoginViewController().password.text!)"
SyncUser.logIn(with: SyncCredentials.usernamePassword(username: username, password: password, register: true), server: URL(string: "http://000.000.000.000:9080")!) { (user, error) in
guard let user = user else {
fatalError(String(describing: error))
}
DispatchQueue.main.async {
let configuration = Realm.Configuration(syncConfiguration: SyncConfiguration(user: user, realmURL: URL(string: "realm://000.000.000.000:9080/~/realmList")!))
let realm = try! Realm(configuration: configuration)
self.lists = realm.objects(List.self).sorted(byKeyPath: "created", ascending: false)
self.notificationToken = self.lists.addNotificationBlock { [weak self] (changes: RealmCollectionChange) in
guard (self?.collectionView) != nil else { return }
switch changes {
case .initial:
self?.collectionView.reloadData()
break
case .update(_, let deletions, let insertions, let modifications):
self?.collectionView.performBatchUpdates({
self?.collectionView.insertItems(at: insertions.map({ IndexPath(row: $0, section: 0)}))
self?.collectionView.deleteItems(at: deletions.map({ IndexPath(row: $0, section: 0)}))
self?.collectionView.reloadItems(at: modifications.map({ IndexPath(row: $0, section: 0)}))
}, completion: nil)
break
case .error(let error):
print(error.localizedDescription)
break
}
}
}
}
}
Realm does not provide an API to convert a standalone Realm to a synced Realm currently. If my understanding is correct, it is necessary to copy the data from the seed Realm to synced Realm when opening the synced Realm.
Related
I have created a protocol called TermProtocol with a function inside called gotTerm. Whenever the user presses this button in my view(CategoryView), the delegate is supposed to get a callback and run the code that I have set. The delegate in my case would be the AppDelegate. I put a print statement in the function called gotTerm in the app delegate so that I could see if the code was really running, but I never saw the phrase I put in the print statement in the console. I don't think my delegate is getting a callback. can anyone help me, please?
Here is my code:
TermProtocol:
protocol TermProtocol: class{
func gotTerm()
}
CategoryView.Swift
struct CategoryView: View {
var foodCategory: String
let appDelegate = UIApplication.shared.delegate as? AppDelegate
var delegate: TermProtocol?
var body: some View {
NavigationView {
NavigationLink(destination: RestrauntView()) {
Image("Find Button")
.renderingMode(.original)
}.simultaneousGesture(TapGesture().onEnded{
print("didtapallow 4")
self.appDelegate!.terms = self.foodCategory
self.delegate?.gotTerm()
})
Spacer()
}
}
}
struct CategoryView_Previews: PreviewProvider {
static var previews: some View {
CategoryView(foodCategory: "Chinese Food")
}
}
AppDelegate.swift
import UIKit
import CoreData
import Moya
import Alamofire
import CoreLocation
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, TermProtocol {
func gotTerm() {
print("did get term")
let lat = self.locationService.setup(latOrLong: "lat")
let long = self.locationService.setup(latOrLong: "long")
self.locationService.lat = lat
self.locationService.long = long
self.loadBusinesses(lat: lat, long: long, theTerm: self.terms)
}
var theViewModels = [RestrauntListViewModel]()
let locationService = LocationService()
var terms = ""
var categoryView = CategoryView(foodCategory: "indian")
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
categoryView.delegate = self
let dataSource = DataSource()
print("this is the view models in appDelegate: \(theViewModels)")
locationService.didChangeStatus = { [weak self] success in
print("did tap allow 1")
if success {
self?.locationService.getLocation()
}
}
locationService.newLocation = { [weak self] result in
print("did tap allow 2")
switch result {
case .success(let location):
self?.loadBusinesses(lat: location.coordinate.latitude, long: location.coordinate.longitude, theTerm: "chinese")
case .failure(let error):
assertionFailure("Error getting the users location \(error)")
}
}
locationService.setup(latOrLong: "lat")
return true
}
func loadBusinesses (lat: Double, long: Double, theTerm: String) {
let service = MoyaProvider<YelpService.BusinessProvider>()
let jsonDecoder = JSONDecoder()
let restrauntView = RestrauntView()
let appDelegate = AppDelegate()
print("The latitude of u is \(lat) and the long of you is \(long)")
if CLLocationManager.locationServicesEnabled() {
switch CLLocationManager.authorizationStatus() {
case .notDetermined, .restricted, .denied:
print("No access")
case .authorizedAlways, .authorizedWhenInUse:
print("Access")
service.request(.search(lat: lat, long: long, term: theTerm)) { (result) in
switch result{
case.success(let response):
print("yaya")
let root = try? jsonDecoder.decode(Root.self, from: response.data)
let viewModels = root?.businesses.compactMap(RestrauntListViewModel.init)
let dataSource = DataSource()
dataSource.arrayOfImages.removeAll()
for image in viewModels! {
Alamofire.request(image.imageURL).responseImage { response in
if let image = response.result.value {
print("image downloadedline 59 appdelegate")
dataSource.arrayOfImages.append(image)
print(dataSource.arrayOfImages)
} else {
print("ERROR: image does not = response.result.value")
}
}
}
self.theViewModels = (root?.businesses.compactMap(RestrauntListViewModel.init))!
print(" restrauntView.theViewModels is here \(restrauntView.theViewModels)")
print("the constant theViewModels in the appdelegate has \(appDelegate.theViewModels.count) values")
case .failure(let error):
print("Error: \(error)")
}
}
#unknown default:
break
}
} else {
print("Location services are not enabled")
}
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "Actrual_Food_Circle")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
I'll start by stating that you shouldn't use delegates and closures this way in SwiftUI. Here's a pretty good intro into clean MVVM architecture using SwiftUI - https://nalexn.github.io/clean-architecture-swiftui/.
I believe you would want to add ViewModel for handling those states in your application.
Going back to answering your question - I think that in this context adding closures would be the quickest(not necessarily right) solution:
struct ContentView: View {
var gotTermCallback: (()->())?
var body: some View {
NavigationView {
NavigationLink(destination: Text("test")) {
...
}.simultaneousGesture(TapGesture().onEnded{
...
self.gotTermCallback?()
})
...
}
}
}
And then in you can add it to some kind of handler or side effect handler by simply calling the following code:
var contentView: ContentView = ContentView()
contentView.gotTermCallback = {
print("[DEBUG] - terms callback")
}
I'm experiencing freezes on the main thread after deleting 10,000 objects out of 500,000 on a background thread. Insertions, however, don't cause this issue.
The trigger is the Results observer on the main thread.
Is this a bug in Realm or am I missing something?
Here is an example that produces the mentioned behavior:
AppDelegate
var realm: Realm!
var token: NotificationToken?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
realm = try! Realm()
token = realm.objects(Item.self).observe { change in
switch change {
case let .update(_, deletions, insertions, modifications):
print("deletions: \(deletions.count)")
print("insertions: \(insertions.count)")
print("modifications: \(modifications.count)")
default:
break
}
}
// addItemsAsync(count: 600000)
deleteItemsAsync(count: 10000)
return true
}
Adding items
func addItemsAsync(count: Int) {
DispatchQueue.global().async {
autoreleasepool {
let realm = try! Realm()
try! realm.write {
for i in 0..<count {
realm.create(Item.self, value: ["id": i])
}
}
}
}
}
Deleting items
func deleteItemsAsync(count: Int) {
DispatchQueue.global().async {
autoreleasepool {
let realm = try! Realm()
let itemsToDelete = realm.objects(Item.self).filter("id < \(count)")
try! realm.write {
realm.delete(itemsToDelete)
}
}
}
}
Item
class Item: Object {
#objc dynamic var id = 0
}
I also noticed that, unlike insertions, a deletion of this sort doesn't simply notify the observer with 10,000 deletions, but instead I get this here once the results are updated on the main thread:
deletions: 20000
insertions: 10000
modifications: 0
This is obviously due to re-ordering. But I would have expected that Realm updates the results in the background and then simply swaps it on the main thread (especially these kind of expensive operations).
Realm not thread safe. If you want to use in different thread you can use ThreadSafeReference.
According to the:
Proper Realm usage patterns/best practices
What is the best practice or design pattern to maintain sync activity across multiple views
Design Pattern for Realm Database Swift 3.1 - Singleton
my approach is like:
AppDelegate.swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
DispatchQueue.main.async {
let username = "test#test.com"
let password = "Test123"
let serverUrl = URL(string: "http://test.com:9080")
let realmUrl = URL(string: "realm://test.com:9080/~/realmtest")
if let user = SyncUser.current {
Realm.Configuration.defaultConfiguration.syncConfiguration = SyncConfiguration(user: user, realmURL: realmUrl!)
} else {
SyncUser.logIn(with: .usernamePassword(username: username, password: password, register: false), server: serverUrl!, onCompletion: { (user, error) in
guard let user = user else {
print("Error: \(String(describing: error?.localizedDescription))")
return
}
Realm.Configuration.defaultConfiguration.syncConfiguration = SyncConfiguration(user: user, realmURL: realmUrl!)
})
}
}
return true
}
ViewController.swift
override func viewDidLoad() {
super.viewDidLoad()
print("SyncConfiguration: \(String(describing: Realm.Configuration.defaultConfiguration.syncConfiguration))")
self.realm = try! Realm()
}
When I open app for the first time nothing happens but when I open app the second time, Realm works fine.
Whenever I open app, the printed SyncConfiguration is nil. No errors!
Searched here and there and can't find an answer...
The problem is that you are using an async method to configure your Realm, but you don't call the print inside the completion handler of your method. You should only present your viewcontoller once your asynchronous call has finished.
I'm new to realm, and so as I was fooling around with it to learn it, I found something quite interesting. In my appDelegate:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let directory: NSURL = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier("group.Hobo.RealmDatabase")!
var config = Realm.Configuration()
config.fileURL = directory.filePathURL?.URLByAppendingPathComponent("db.realm")
Realm.Configuration.defaultConfiguration = config
let realm = try! Realm()
print("File Location: \(realm.configuration.fileURL!)") // -> Location A
print("NO OF USERS: \(realm.objects(User).count)") // -> 0
return true
}
but in my ViewController:
let realm = try! Realm()
override func viewDidLoad() {
super.viewDidLoad()
print("NO OF USERS IN VIEWDIDLOAD: \(realm.objects(User).count)") // -> 1
let firstTime = loadFirstTime()
if firstTime {
// configure USER!
let user = User()
user.monthlyIncome = 50000
try! realm.write({
realm.add(user)
})
saveFirstTime(false)
print("First time, user written")
}
dailyLimit.text = String(realm.objects(User).first!.dailyLimit)
}
Notice the returns from the print() functions. In app delegate, the result of the print(number of users:) returns 0, but in the viewController's viewDidLoad, it returned a 1.
Isn't both supposed to return the same value? In this case 1?
Thanks in advance!!
Yes it is the same, I'm guessing you removing by mistake the user, on application load, or something like that, you should use "Realm browser" to check your DB state, that way you can see when an object changes during run time. https://github.com/realm/realm-browser-osx
EDIT
Check your accessing the default configuration. In realm you can have multiple configurations like so:
let config = Realm.Configuration(
// Get the URL to the bundled file
fileURL: NSBundle.mainBundle().URLForResource("MyBundledData", withExtension: "realm"),
// Open the file in read-only mode as application bundles are not writeable
readOnly: true)
// Open the Realm with the configuration
let realm = try! Realm(configuration: config)
depend on documentation of realm 3
https://realm.io/docs/swift/latest/#realm-configuration
func setDefaultRealmForUser(username: String) {
var config = Realm.Configuration()
// Use the default directory, but replace the filename with the username
config.fileURL = config.fileURL!.deletingLastPathComponent().appendingPathComponent("\(username).realm")
// Set this as the configuration used for the default Realm
Realm.Configuration.defaultConfiguration = config
}
Attached is my code below.
The line that is giving me the problems is let fetchRequest = try moc.executeFetchRequest(fetchRequest) as! [AppSettings] appears to load asynchronously but I want it to load synchronously so that I can ensure it checks properly for a username record.
How do I do this?
I know it loads asynchronously because when I start and stop the program constantly it will find the entity roughly 80% of the time and randomly 20% of the time it will not. Since nothing else is changing the entity (since I'm just starting and stopping the program constantly), it would make sense that the code is being run asynchrnously so when I use the command
guard let appSettingsArrayItem = fetchRequest.first where fetchRequest.count>0 else {
print ("no entities found...")
return false
}
It fails to find any entities sometimes.
Check Login Function
func checkIfLoggedInAlready() -> Bool{
let fetchRequest = NSFetchRequest(entityName: "AppSettings")
//let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest) //Deletes ALL appsettings entities
do {
let fetchRequest = try moc.executeFetchRequest(fetchRequest) as! [AppSettings]
guard let appSettingsArrayItem = fetchRequest.first where fetchRequest.count>0 else {
print ("no entities found...")
return false
}
guard let username = (appSettingsArrayItem as AppSettings).username else{
print ("username not found")
return false
}
print("number Of AppSetting Entities =\(fetchRequest.count)")
print(username)
//The following code deletes ALL the entities!
//try moc.persistentStoreCoordinator!.executeRequest(deleteRequest, withContext: moc)
//To delete just '1' entry use the code below.
//moc.deleteObject(appSettingsArrayItem)
//try moc.save()//save deletion change.
//print("deleted particular entity item")
return true
} catch{
fatalError("bad things happened \(error)")
}
}
Entire LoginViewController including Check Login Function
import UIKit
import CoreData
class LoginViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var usernameField: UITextField!
#IBOutlet weak var passwordField: UITextField!
var isLoggedIn = false
let moc = DataController().managedObjectContext
#IBAction func SignUpButtonPressed(sender: UIButton) {
print("sign up")
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func textFieldShouldEndEditing(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
override func viewDidLoad() {
super.viewDidLoad()
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
view.addGestureRecognizer(tap)
print("view loaded, check if already signed in here")
let loggedIn = checkIfLoggedInAlready() //checks database to see
if(loggedIn){
print("was logged in!")
isLoggedIn = true
self.performSegueWithIdentifier("loginSegue", sender: self)
}
}
func checkIfLoggedInAlready() -> Bool{
let fetchRequest = NSFetchRequest(entityName: "AppSettings")
//let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest) //Deletes ALL appsettings entities
do {
let fetchRequest = try moc.executeFetchRequest(fetchRequest) as! [AppSettings]
guard let appSettingsArrayItem = fetchRequest.first where fetchRequest.count>0 else {
print ("no entities found...")
return false
}
guard let username = (appSettingsArrayItem as AppSettings).username else{
print ("username not found")
return false
}
print("number Of AppSetting Entities =\(fetchRequest.count)")
print(username)
//The following code deletes ALL the entities!
//try moc.persistentStoreCoordinator!.executeRequest(deleteRequest, withContext: moc)
//To delete just '1' entry use the code below.
//moc.deleteObject(appSettingsArrayItem)
//try moc.save()//save deletion change.
//print("deleted particular entity item")
return true
} catch{
fatalError("bad things happened \(error)")
}
}
func dismissKeyboard() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
print("prepare seque")
}
func displayErrorMessage(errorMessage: String){
print("show error console with Error:"+errorMessage)
let alert = UIAlertController(title: "Error", message: errorMessage, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool {
switch(identifier){
case "loginSegue":
print("Is the user already logged in?")
if(isLoggedIn){
print("Detected as YES")
return true
}
print("Detected as NO, so checking username and password fields next...")
guard let password = passwordField.text!.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet()) where !password.isEmpty else {
displayErrorMessage("Password can not be empty!")
return false
}
guard let username = usernameField.text!.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet()) where !username.isEmpty else{
displayErrorMessage("Username can not be empty!")
return false
}
let url = "http://distribution.tech/restapi/v1/userlogin?email="+username+"&password="+password
print(url)
let json = JSON(url:url)
print(json)
if(json["status"].asInt==1){
let entity = NSEntityDescription.insertNewObjectForEntityForName("AppSettings", inManagedObjectContext: moc) as! AppSettings
entity.setValue(username, forKey: "username")
entity.setValue(password, forKey: "password")
entity.setValue(json["tokenid"].asString, forKey: "token")
entity.setValue(json["roleid"].asInt, forKey: "roleid")
entity.setValue(json["role"].asString, forKey: "role")
entity.setValue(json["companyid"].asInt , forKey: "companyid")
entity.setValue(json["isdev"].asInt, forKey: "isdev")
//save token and other details to database.
do {
try moc.save()
print("saved to entity")
}catch{
fatalError("Failure to save context: \(error)")
}
// token
// roleid int
// role
// companyid int
//
// {
// "companyid": 3,
// "userid": 2,
// "tokenid": "804febae26ddbd0292b3d2c66b30afd5028d5ba9",
// "status": 1,
// "roleId": 1,
// "role": "super_admin",
// "isdev": 0
// }
//Save to disk using our own method, as COREDATA is unreliable!
return true //login succesfull
}else{
displayErrorMessage("Incorrect Username or Email")
return false//failed
}
default:
displayErrorMessage("Unknown Error Related To Segue Not Found")
}
return false //if it gets to this point assume false
}
}
The managed object is created in the DataController its file is here below.
import UIKit
import CoreData
class DataController: NSObject {
var managedObjectContext: NSManagedObjectContext
override init() {
// This resource is the same name as your xcdatamodeld contained in your project.
guard let modelURL = NSBundle.mainBundle().URLForResource("AppSettings", withExtension:"momd") else {
fatalError("Error loading model from bundle")
}
// The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
guard let mom = NSManagedObjectModel(contentsOfURL: modelURL) else {
fatalError("Error initializing mom from: \(modelURL)")
}
let psc = NSPersistentStoreCoordinator(managedObjectModel: mom)
self.managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
self.managedObjectContext.persistentStoreCoordinator = psc
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
let docURL = urls[urls.endIndex-1]
/* The directory the application uses to store the Core Data store file.
This code uses a file named "DataModel.sqlite" in the application's documents directory.
*/
let storeURL = docURL.URLByAppendingPathComponent("AppSettings.sqlite")
do {
try psc.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil)
} catch {
fatalError("Error migrating store: \(error)")
}
}
}
}
Image Reference Of Entity & Console Error That Can Happen Sometimes
Image Reference Of Entity & Console When It Does Find Entity Most Of Time
ManagedObjectContext.ExecuteFetchRequest already runs synchronously but it looks like you are setting up your persistent store coordinator asynchronously in a background priority thread.
If this fetch request happens immediately when the app starts up, and you do it over and over again, it may not be finished setting up some of the times.
Okay the answer above was correct, so what I did was created a new project single view, selected core data option, and copied code from its AppDelegate over my own AppDelegate to get the proper CoreData Init Code, and in such a way that when the project terminates it saves the context correctly and so forth. The code looks like this.
import UIKit
import CoreData
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.distribution.tech.Test" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("AppSettings", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("AppSettings.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
Its key when you do this that you change the reference to your own xcdatamodeld or this won't work. In my case it was changing this line to the correct sqlite based on my previous work.
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("AppSettings.sqlite")
and this line...
let modelURL = NSBundle.mainBundle().URLForResource("AppSettings", withExtension: "momd")!
which is the actual name of the xcdatamodeld file.
Hope this helps someone who had same issue as me. Oh...and apple if you are reading this...please add 'core data' option for tab based projects in the future... and not just single view.