Reputation: 31
I'm trying to add a property observer in my class ChooserListVC for "list"
These are the variables in ChooserSaves that I would like to track.
class ChooserSaves: UIDocument {
var savedListObject : SavedList?
var listName : String = ""
var chooserItems : [String] = []
}
Im not sure how to set this up in the class I'm implementing it.
class ChooserListVC: UIViewController, UITableViewDelegate, UITableViewDataSource,UITextFieldDelegate{
var list : ChooserSaves!
I tried to do something like this:
var list : ChooserSaves!{
didSet{
if chooserItems.count > 0{
println("didset greater than 1")
}
else{
println("didset less than 1")
}
}
}
But this only works once when the segue assigns the list. How can I make it so that every time I change list.chooserItems
in other bits of code, it would trigger the correct line?
Upvotes: 1
Views: 1544
Reputation: 31
I didn't find it the way I wanted, but I found a different way to do it. I added notifications in the class I was implementing. Then I just added a listener to trigger the event I needed.
class ChooserSaves: UIDocument {
var savedListObject : SavedList?
var listName : String = ""
var chooserItems : [String] = []{
didSet{
if chooserItems.isEmpty{
NSNotificationCenter.defaultCenter().postNotificationName(listEmpty, object: nil)
}
else{
NSNotificationCenter.defaultCenter().postNotificationName(listNotEmpty, object: self)
}
}
}
and this was how added the listener in the class I used the object in.
NSNotificationCenter.defaultCenter().addObserver(self, selector: "deactivateControls", name: listEmpty, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "activateControls", name: listNotEmpty, object: nil)
Upvotes: 0
Reputation: 403
The easiest solution would be to set your property you want to observe to private and create publicly available methods to manipulate your array.
...
private var chooserItems: [String] = []
...
func add(chooserItem: String){
// your tracking logic here
// update your private array
self.chooserItems.append(chooserItem)
...
}
...
If you need real observation, I'd suggest to checkout this answer Is key-value observation (KVO) available in Swift?
Upvotes: 1