2015-05-06 20 views
3

这是我的代码。看来,当我继承UIColor,使其equatable我得到一个内存错误。这是为什么?实现快速等值协议会导致访问错误。为什么?

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") 
} 

enter image description here

+0

可能无关的错误,但是您的代码不是来自'MyColor任何不同(名: “coolRed” 中,r:1,G 1,B:1)'和'MyColor(名称:“ coolBlue“,r:1,g:1,b:1)' – nhgrif

+0

我知道实际的颜色没有任何不同,但与错误无关..这不是完美的代码。我附上了错误的屏幕截图 – hamobi

+0

对于任何感兴趣的人,只需将此问题中的代码复制并粘贴到沙盒中即可生成相同的错误。 – nhgrif

回答

2

的UIColor是一类集群,子类应该避免。

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

这段代码是“操场就绪”的。

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 
相关问题