在Swift中编写自定义访问器方法

时间:2015-11-12 14:27:52

标签: swift core-data accessor

我想将核心数据动态生成的访问器方法覆盖为can be done in Objective-C

例如,当Team name nil Player代替name class Team: NSManagedObject { @NSManaged var name: String { // Error: @NSManaged not allowed on computed properties get { self.willAccessValueForKey("name") var teamName = self.primitiveValueForKey("name") self.didAccessValueForKey("name") return teamName ?? (self.players.firstObject as! Player).name } } @NSManaged var breakPoints: NSOrderedSet @NSManaged var gamesWon: NSOrderedSet @NSManaged var matches: NSOrderedSet @NSManaged var matchesWon: NSOrderedSet @NSManaged var players: NSOrderedSet @NSManaged var pointsWon: NSOrderedSet @NSManaged var setsWon: NSOrderedSet } 时,

类似的东西:

Team

同时保持存储的值不变,并透明地更改已访问name的{​​{1}}的对象所读取的值。

1 个答案:

答案 0 :(得分:3)

您不会在Swift中覆盖Core Data访问器。而是创建单独的计算属性。

@NSManaged var actualName: String
var name: String {
 get { 
   self.willAccessValueForKey("actualName")
   let teamName = self.primitiveValueForKey("actualName")
   self.didAccessValueForKey("actualName")

   return teamName ?? (self.players.first as! Player).name
 }
 set {
   name = newValue
   // omitting KVC markers here
   actualName = newValue
 }
}