Mikael
Mikael

Reputation: 2395

CoreData with Swift and iOS 8+ still needs willAccessValueForKey()?

I'm writing a function in my NSManagedObject subclass called Friend.

I wonder if I should write this (user is another NSManagedObject User):

  func firstCharacterOfComputerDisplayName() -> String
  {
    guard let user = self.friend else {
      return ""
    }
    return user.firstCharacterOfComputerDisplayName()
  }

or that:

  func firstCharacterOfComputerDisplayName() -> String
  {
    self.willAccessValue(forKey: "friend")

    guard let user = self.primitiveValueForKey("friend") as? User else {
      self.didAccessValue(forKey: "friend")
      return ""
    }
    let dispName = user.firstCharacterOfComputerDisplayName()
    self.didAccessValue(forKey: "friend")
    return dispName
  }

Upvotes: 0

Views: 463

Answers (1)

Tom Harrington
Tom Harrington

Reputation: 70966

Whether to use willAccessValue(forKey:), primitiveValueForKey(_:) and didAccessValue(forKey:) isn't related to whether you use Swift or iOS 8. It's strictly a Core Data thing. Core Data uses KVO to maintain data graph integrity and so on, so it has certain expectations about when it will observe changes and access.

Mostly you don't need to care about those methods unless you are overriding an accessor method. If you want the value of self.friend, just ask for it as self.friend. Unless you're overriding the accessors for friend, except you're not doing that here.

Upvotes: 1

Related Questions