[英]UIImages: should I use stored or computed properties?
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.基本上我的情况是,我的
ViewController
中多次出现相同的 UIImage ,我不确定影响是什么。
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.考虑一个 TableView,其中每个单元格对应一个 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
?不断地用
myimageview.image = UIImage(named: myobject.imagename)
实例化图像而不是仅仅实例化一次并用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?或者 Swift 在知道图像已经加载过一次的情况下,会在后台优化它吗?
iOS has an UIImage
cache, so calling UIImage(named: myobject.imagename)
multiple times for the same image is perfectly fine. iOS 有一个
UIImage
缓存,所以多次调用UIImage(named: myobject.imagename)
对同一个图像是非常好的。
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).使用
init(named:in:compatibleWith:)
方法(或init(named:)
方法)从位于应用程序主包(或其他已知包)中的图像资产或图像文件创建图像。 Because these methods cache the image data automatically , they're especially recommended for images that you use frequently.由于这些方法会自动缓存图像数据,因此特别推荐用于您经常使用的图像。
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使用计算属性或存储属性背后的想法是当属性的值随时间改变或不改变时,给定 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因此,如果
myName
随时间变化,那么您需要将myImage
设为计算属性以始终获取最新更新的图像,但如果myName
仅设置一次,则需要将其设为存储属性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.