How to set a core-data attibute to nil, in Swift?

1.9k views Asked by At

Here is a working Swift function I have:

func myColorFuntion (object:NSManagedObject) -> UIColor {
    if (object.valueForKey("bgColor") == nil) {return UIColor.yellowColor()}
    return NSKeyedUnarchiver.unarchiveObjectWithData(object.valueForKey("bgColor") as! NSData) as! UIColor
}

My question relates to the line with the “if” statement. object.valueForKey("bgColor") starts with a nil value because it has not been defined. I can set something not nil for object.valueForKey("bgColor") with code like the following and it works.

let theColorData:NSData = NSKeyedArchiver.archivedDataWithRootObject(UIColor.cyanColor())
var object:NSManagedObject
object.setValue(theColorData forKey:"bgColor")

But how can I set object.valueForKey("bgColor") back to nil? The few trials I made using nil and NSNull didn’t work.

`

1

There are 1 answers

0
eGanges On

In Swift 4, try:

object.setNilValueForKey("your attribute name")