Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSManagedObject.setValue(value: AnyObject?, forKey key: String) causes error in Swift 2.0

Tags:

swift2

I have this piece of code which was working ok in XCode6 (Swift 1.2) but not with the Swift 2:

class func findOrCreate<T: NSManagedObject>(type: T.Type, attribute: String, value: AnyObject?) -> T {
    if let object = T.MR_findFirstByAttribute(attribute, withValue: value) as? T {
        return object
    } else {
        let object = T.MR_createEntity() as! T
        if let value:AnyObject = value {
            object.setValue(value, forKey: attribute)
        }
        return object
    }
}

Error shows on the line containing object.setValue with the message:

Ambiguous use of 'setValue(_:forKey:)'

I think it does not recognise object to be of NSManagedObject type but I'm not 100% sure, any clue why this happens much appreciated.

like image 961
Mahakala Avatar asked Oct 10 '15 12:10

Mahakala


2 Answers

I've posted same question on Apple Forum and got an answer with a workaround for this problem:

      let object = T.MR_createEntity() as! NSManagedObject
      if let value:AnyObject = value {   
           object.setValue(value, forKey: attribute)   
      }   
      return object as! T

This works as expected. I've submitted a bug report to Apple as well.

like image 112
Mahakala Avatar answered Oct 12 '22 00:10

Mahakala


One more possible solution is this:

(object as NSManagedObject).setValue(value, forKey: attribute)
like image 29
Nikita Ivaniushchenko Avatar answered Oct 12 '22 01:10

Nikita Ivaniushchenko