user9050369
user9050369

Reputation:

How save default Boolean to the coreData as a true or false?

import UIKit
import CoreData
var kind = true

two buttons in a customTableViewCell.

    protocol KindTableViewCellDelegate: class {
    func kindTableViewCellDidTapReceive(_ kindTableViewCell: KindTableViewCell)
    func kindTableViewCellDidTapPaid(_ kindTableViewCell: KindTableViewCell)
}
class KindTableViewCell: UITableViewCell {
    let check  = Checks(context: PersistentService.context)

    @IBOutlet weak var paidButton: UIButton!
    @IBOutlet weak var recivedButton: UIButton!
    var delegate: KindTableViewCellDelegate?



    @IBAction func paidButtonClicked(_ sender: Any) {
        paidButton.setImage(#imageLiteral(resourceName: "red on"), for: UIControlState.normal)
        recivedButton.setImage(#imageLiteral(resourceName: "green off"), for: UIControlState.normal)
        delegate?.kindTableViewCellDidTapReceive(self)
        kind = true
        check.kind = kind

    }

    @IBAction func recivedButtonClicked(_ sender: Any) {
        recivedButton.setImage(#imageLiteral(resourceName: "green on"), for: UIControlState.normal)
        paidButton.setImage(#imageLiteral(resourceName: "red off"), for: UIControlState.normal)
        delegate?.kindTableViewCellDidTapPaid(self)
        kind = false
        check.kind = kind

    }

in normal with this code, the boolean kind is null in CoreData . I want to save default true to CoreData.

Upvotes: 0

Views: 1121

Answers (1)

Iraniya Naynesh
Iraniya Naynesh

Reputation: 1165

You can do that without code, Click on your xcDatamodel select your entity than your attribute, then on the right side you will get all the properties set yes as defaultenter image description here

InCase you want to do by code when creating the check set kind to true

let check  = Checks(context: PersistentService.context)
check.kind = true //default value 
context.save() // save your context

Or overriding awakeFromInsert method

awakeFromInsert is invoked only once in the lifetime of an object—when it is first created.

override func awakeFromInsert() {
    super.awakeFromInsert()
    kind = true
}

And in your case, if

kind = false
check.kind = kind 
context.save() //   save context after setting value. 

Is this still showing nil in the database then there is something wrong with your attribute or context, as in database is should have set true for paidButtonClicked and false for recivedButtonClicked and no way nil. check setting other attributes so you know whats going wrong.

Upvotes: 5

Related Questions