导致崩溃的属性

时间:2017-01-13 05:05:44

标签: swift xcode attributes

我最近在swift中编写了这段代码,但由于某种原因它崩溃了应用程序。

class ShapeColour : NSObject {
        var colour = ""
        var shape = ""
        var images = UIImage(named: "")
    }

    //Blue Square

    let BlueSquareObject =  ShapeColour()
    BlueSquareObject.setValue("Blue", forKey: "colour")
    BlueSquareObject.setValue("square", forKey: "shape")
    BlueSquareObject.setValue("BlueSquare.jpg", forKey: "images")

    //Red Square

    let RedSquareObject =  ShapeColour()
    RedSquareObject.setValue("Red", forKey: "colour")
    RedSquareObject.setValue("square", forKey: "shape")
    RedSquareObject.setValue("RedSquare.jpg", forKey: "images")

    //Yellow Square

    let YellowSquareObject =  ShapeColour()
    YellowSquareObject.setValue("Yellow", forKey: "colour")
    YellowSquareObject.setValue("square", forKey: "shape")
    YellowSquareObject.setValue("YellowSquare.jpg", forKey: "images")

创建属性时我做错了吗?任何帮助将不胜感激;)

谢谢!

1 个答案:

答案 0 :(得分:0)

images

ShapeColour属性类型为UIImage,您正在设置String

BlueSquareObject.setValue(UIImage(named: "BlueSquare.jpg"), forKey: "images")

您需要遵循一些编码指南,例如以小写字母开头的对象名称。另外,创建对象的最简单方法是使用init,这也会减少您的代码,所以我建议您像这样在init类中添加一个ShapeColour方法。

class ShapeColour : NSObject {
    var colour:String
    var shape:String
    var images: UIImage

    init(color: String, shape: String, image: UIImage) {
        self.colour = color
        self.shape = shape
        self.image = image
    }
}

现在只需致电init即可创建ShapeColour的实例。

let blueSquareObject =  ShapeColour(color: "Blue", shape: "square", image: UIImage(named: "BlueSquare.jpg"))