【问题标题】:Implementing swift equatable protocol gives me bad access error. why?实施 swift equatable 协议给了我糟糕的访问错误。为什么?
【发布时间】:2015-05-06 23:36:22
【问题描述】:

这是我的代码。似乎当我将 UIColor 子类化以使其相等时,我得到了一个内存错误。这是为什么呢?

class MyColor: UIColor, Equatable {
    var name: String


    init(name: String, r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat = 1.0) {
        self.name = name
        super.init(red: r, green: g, blue: b, alpha: a)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

func == (lhs: MyColor, rhs: MyColor) -> Bool {
    return lhs.name == rhs.name
}

let test1 = MyColor(name: "coolRed", r: 10, g: 12, b: 22)

let test2 = MyColor(name: "coolBlue", r: 10, g: 12, b: 22)


if test1 == test2 {
    println("hey")
}

【问题讨论】:

  • 可能与您的错误无关,但您的代码与MyColor(name: "coolRed", r:1, g:1, b:1)MyColor(name: "coolBlue", r:1, g:1, b:1) 没有任何不同
  • 我知道实际的颜色并没有什么不同,但这与错误无关......此时它不是完美的代码。我附上了错误的截图
  • 对于任何感兴趣的人,只需将此问题中的代码复制并粘贴到沙箱中就会产生相同的错误。
  • 可能与您的问题无关(这就是为什么这是评论,而不是答案),但UIColor reference 似乎警告不要继承 UIColor。另请参阅this stackoverflow question
  • @zpasternack 我认为这实际上是问题所在。我使用其他类没有这个问题

标签: ios swift compiler-errors protocols


【解决方案1】:

UIColor 是类簇,应避免子类化。

您可以使用 Objective-C 运行时来获得您想要的功能。

这个 sn-p 已经“准备就绪”了。

import UIKit

let _nameKey = malloc(4)

extension UIColor : Equatable {

var name : String {
    get {
        return objc_getAssociatedObject(self, _nameKey) as! String
    }
    set {
         objc_setAssociatedObject(self,
            _nameKey,
            newValue,
            UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        );
    }
}
}


public func ==(lhs: UIColor, rhs: UIColor) -> Bool {
    return lhs.name == rhs.name
}

let aRed = UIColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 0.0)
aRed.name = "Red"
aRed.name

let anotherRed = UIColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 0.0)
anotherRed.name = "Red"

aRed == anotherRed

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-02
    • 1970-01-01
    • 2017-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多