Joseph Astrahan
Joseph Astrahan

Reputation: 9072

Global Variables For Core Data Classes (Bad?, Good?)

I have a file called globals.swift

The code is very simple and looks like this.

import Foundation
import CoreData
import UIKit

var g_workOrders = [Workorders]()
var g_services = [Service]()

//Shortcut method to get the viewcontext easily from anywhere.
func gm_getContext () -> NSManagedObjectContext {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext

    //For unique constraints it will overwrite the data.
    context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy

    return context
}

My data model is very simple, its a workorder which refers to a 'service' which in my context can be thought of as a description for the workorder. Workorders can only have one 'service'. A 'service' can belong to many workorders but does not have a relationship to many of them. So its a one to one I believe still.

g_workOrders[] and g_services[] are NSManagedSubclasses that I created from the editor menu -> createNSManagedSubClasses.

I plan to use these arrays throughout the program to keep track of the current state of work orders and get info on a service at anytime. Furthermore if I update the global variables and call save on the context it should save the database. This does currently work but my question is...is this good practice? Can any unexpected behavior result from doing it this way?

Upvotes: 0

Views: 777

Answers (2)

Mundi
Mundi

Reputation: 80273

Your approach is questionable for mainly two reasons: It hogs memory, and it has potential inconsistencies if the db changes and your array objects are not in sync.

You should use NSFetchedResultsController wherever you need this data. Core Data will do all optimizations for you and give you lots of functionality for free (e.g., ideal for table views).

Also, one of your statement is contradictory and might point to a design flaw:

A 'service' can belong to many workorders but does not have a relationship to many of them.

This is definitely wrong. If the same Service can belong to many Workorders, it should have a to-many relationship to the Workorder entity and a reverse to-one relationship.

Upvotes: 1

GetSwifty
GetSwifty

Reputation: 7746

You can do things this way, but you don't really need to.

You can simply get all the objects of the type you want with a fetch request whenever you need them. CoreData is highly optimized and cached so unless you're dealing with extreme numbers there shouldn't ever be a meaningful wait time. This way you know you will always have all the instances of your models without trying to manage their state in another place.

Also, if you have a connection between WorkOrders and Service in the database. (which you should), you definitely don't need to keep arrays of both of them to begin with.

Upvotes: 1

Related Questions