简体   繁体   English

Swift与对象的属性观察器

[英]Property Observer for Swift with Objects

I'm trying to add a property observer in my class ChooserListVC for "list" 我试图在我的类ChooserListVC中为“列表”添加一个属性观察器

These are the variables in ChooserSaves that I would like to track. 这些是我想跟踪的ChooserSaves中的变量。

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. 但这仅在segue分配列表时起作用。 How can I make it so that every time I change list.chooserItems in other bits of code, it would trigger the correct line? list.chooserItems ,以便每次我在其他代码位中更改list.chooserItems时,都会触发正确的行?

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? 如果您需要真正的观察,我建议您查看此答案。Swift中是否提供键值观察(KVO)?

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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