Implementing a fast peer protocol gives me a bad access error. What for?

here is my code. it seems that when I subclass UIColor to make it equal, I get a memory error. Why is this?

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

+3


source to share


1 answer


UIColor is a cluster of classes, subclassing should be avoided.

You can use the Objective-C runtime to get the functionality you want.



This piece is "ready to play".

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

      

+2


source







All Articles