Search code examples
iosswiftmodel-view-controllercore-data

Does the CoreData support methods?


I have a class with attributes (var and let) and methods. For storing data I use UserDefaults and I try to use MVC. Now I want use CoreData. I can use an entity to store var, but where do I put the methods? Can methods be placed in CoreData? If not, where is it better to place the methods and logic for working with variables? Help me please)

class Statistics {
    var defaults = UserDefaults.standard
    var completed = 0
    var launched = 0
    var minutes = 0
    var today = 0
    var dateNew = 0
    let calendar = Calendar.current
    
    static var passedSecondsBackground = 0
    static var didBackground = false
    
    enum Keys: String {
        case day = "PMDR.Day"
        case week = "PMDR.Week"
        case month = "PMDR.Month"
        case year = "PMDR.Year"
        case completed = "Completed"
        case launched = "Launched"
        case minutes = "Minutes"
    }
    
    var keyCompleted = Keys.completed.rawValue
    var keyLaunched = Keys.launched.rawValue
    var keyMinutes = Keys.minutes.rawValue
    

    func checkDate(array: Array<Statistics>) {
        for date in array {
            date.dateNew = date.defaults.integer(forKey: "\(date)")
            if date.today != date.dateNew {
                date.deleteScore(when: date)
                date.defaults.set(date.today, forKey: "\(date)")
                date.dateNew = date.defaults.integer(forKey: "\(date)")
            }
        }
    }
    
    func updateScore(array: Array<Statistics>) {
        for date in array {
            date.completed = date.defaults.integer(forKey: date.keyCompleted)
            date.launched = date.defaults.integer(forKey: date.keyLaunched)
            date.minutes = date.defaults.integer(forKey: date.keyMinutes)
        }
    }

    /* etc... */
}

Solution

  • There are two options.

    • If the classes are generated by Xcode put your custom logic into extensions of the classes.
    • Create the classes yourself (by setting Codegen to Manual/None and the menu item Editor > Create NSManagedObject Subclass). This way is harder to maintain but you can customize the NSManagedObject subclasses by replacing the optional with non-optional types and the relationship type NSSet with native Set