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
534 views
in Technique[技术] by (71.8m points)

ios8 - Override a setter in swift

I've got a strange problem with setter in swift. I've got class PlayingCard with code:

var rank: NSInteger {
    get{
        return self.rank
    }
    set(rank){
        self.rank = rank
    }
}

var suit: NSString {
    get{
        return self.suit
    }
    set(suit){
        self.suit = suit
    }
}

init(suit: NSString, rank: NSInteger) {
    super.init()
    self.suit = suit
    self.rank = rank
}

I use this init() method in another class, and implementation looks like this:

init() {
    super.init(cards: [])
    for suit in PlayingCrad.validSuit() {
        var rank: Int = 0
        for rank; rank <= PlayingCrad.maxRank(); rank++ {
            var card = PlayingCrad(suit: suit, rank: rank)
            addCard(card)
        }
    }
}

And when the code looks like above I've got a error in line:

self.suit = suit

EXC_BAD_ACCESS(code=2, adress=0x7fff5c4fbff8)

But when I removed setter and getter from rank and suit attribute it's worked fine, no error has shown up.

Can you explain me why this EXC_BAD_ACCESS error has shown up?

Thank you for your help

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

By writing this...

set(suit) {
    self.suit = suit
}

... you introduce an infinite loop, because you call the setter from within the setter.

If your property isn't computed, you should take advantage of willSet and didSet notifiers to perform any additional work before/after the property changes.

By the way, you should remove te getter as well. It will cause another infinite loop when accessing the property.


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

...