Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
507 views
in Technique[技术] by (71.8m points)

Swift - Custom setter on property

I am converting a project in to Swift code and have come across an issue in a setter. My Objective-C code looked like this:

- (void)setDocument:(MyDocument *)document
{
    if (![_document isEqual:document]) {
        _document = document;

        [self useDocument];
    }
}

and allowed my View Controller to run this each time the document was set (typically in the prepareForSegue: method of the presenting View Controller).

I have found the property observers willSet and didSet but they only work when the property is being updated, not when it’s initialised and updated.

Any ideas? Thanks

UPDATE

after trying get{} and set{} I get the EXC_BAD_ACCESS error

var document: UIDocument? {
    get {
        return self.document!
    }
    set {
        self.document = newValue

        useDocument()
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can't use set like that because when you call self.document = newValue you're just calling the setter again; you've created an infinite loop.

What you have to do instead is create a separate property to actually store the value in:

private var _document: UIDocument? = nil
var document: UIDocument? {
    get {
        return self._document
    }
    set {
        self._document = newValue
        useDocument()
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...