简体   繁体   中英

Property Observer for Swift with Objects

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?

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM