I haven’t thought about it much until today. Basically I’m in a situation in which I have the same UIImage appear multiple times in my ViewController
s, and I’m not sure what the impact is.
class MyObjectA{
private(set) var myName: String
var myImage: UIImage? { UIImage(named: myName) } //as computed property
}
class MyObjectB{
private(set) var myName: String
private(set) var myImage: UIImage? //as stored property
init(myName: String){
self.myName = myName
self.myImage = UIImage(named: myName)
}
}
Consider a TableView, where each cell corresponds to an object. Is it bad having an image constantly being instantiated with myimageview.image = UIImage(named: myobject.imagename)
versus just instantiating once and referencing it with myimageview.image = myobect.image
? Or does Swift do some super magic where it optimizes it under the hood, knowing that image was already loaded once?
2
Answers
iOS has an
UIImage
cache, so callingUIImage(named: myobject.imagename)
multiple times for the same image is perfectly fine.The documentation says
The idea behind using a computed property or a stored one is when the value of the property being changed or not with time ,so given ex.1
So if
myName
changes with time then you need to makemyImage
a computed property to always get the latest updated image , but ifmyName
is being set only once then you need to make it a stored property