Swift 导致崩溃的属性
我最近用swift编写了这段代码,但由于某种原因,它使应用程序崩溃Swift 导致崩溃的属性,swift,xcode,attributes,Swift,Xcode,Attributes,我最近用swift编写了这段代码,但由于某种原因,它使应用程序崩溃 class ShapeColour : NSObject { var colour = "" var shape = "" var images = UIImage(named: "") } //Blue Square let BlueSquareObject = ShapeColour() BlueSquareObject.setValue(
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")
创建属性时我是否做错了什么?任何帮助都将不胜感激;)
谢谢
images
类ShapeColour
的属性是UIImage
的类型,您可以使用它设置String
BlueSquareObject.setValue(UIImage(named: "BlueSquare.jpg"), forKey: "images")
您需要遵循一些编码准则,比如对象名以小写字母开头。另外,创建对象的最简单方法是使用init
,这也会减少代码,因此我建议您在shapeclour
类中添加一个init
方法,如下所示
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
即可创建shapeclour
的实例
let blueSquareObject = ShapeColour(color: "Blue", shape: "square", image: UIImage(named: "BlueSquare.jpg"))
你需要用你得到的错误更新你的问题。但是,为什么您试图使用
String
值设置名为images
的UIImage
属性?对不起,我是swift新手。你能解释一下我应该如何使用UIimage吗@rmaddyFirst,使用错误更新您的问题,并指出导致错误的行。我没有收到错误,调试器中唯一的行是“错误:通过进程ID“4585”附加失败无法附加”@RmaddyTanks非常感谢!修复了我的问题,大大缩短了我的代码!(完整的属性列表长了4倍;)@Nosh Welcome mate:)