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 intantiating 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?
CodePudding user response:
iOS has an UIImage
cache, so calling UIImage(named: myobject.imagename)
multiple times for the same image is perfectly fine.
Use the
init(named:in:compatibleWith:)
method (or theinit(named:)
method) to create an image from an image asset or image file located in your app’s main bundle (or some other known bundle). Because these methods cache the image data automatically, they’re especially recommended for images that you use frequently.
CodePudding user response:
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
class MyObjectA{
private(set) var myName: String
var myImage: UIImage? { UIImage(named: myName) } //as computed property
So if myName
changes with time then you need to make myImage
a computed property to always get the latest updated image , but if myName
is being set only once then you need to make it a stored property