xcodeswiftnsarraycontrollernscollectionviewnscollectionviewitem

How to update NSCollectionViewItem when data model change?


I have a NSArrayController bound to a NSCollectionView. My data model is a class Person. Inside Person is a timer that will change the property age every second. In my NSCollectionViewItem I have a NSLabel bound to representedObject.age.

When the application starts the label will show the initial value of age but it will not update afterwards when the value changes. How do I do that?

import Foundation

@objc(Person)
public class Person: NSObject
{
    public var firstName:String
    public var lastName:String
    public var age:Int

    var timer:NSTimer?

    override init()
    {
        self.firstName = "Max"
        self.lastName = "Meier"
        self.age = 33
        super.init()
        self.timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "tick", userInfo: nil, repeats: true)
        self.timer?.fire()
    }

    public func tick()
    {
        self.age++
        println(self.age)
    }
}

Solution

  • Bindings are built on top of Key-Value Observing. In order for a property in Swift to be KVO-compliant, it has to be marked dynamic. So, declare age as:

    dynamic public var age:Int