3

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.

`

Michel
  • 10,303
  • 17
  • 82
  • 179

1 Answers1

3

In Swift 4, try:

object.setNilValueForKey("your attribute name")
davidev
  • 7,694
  • 5
  • 21
  • 56
eGanges
  • 411
  • 3
  • 8