[英]How write getter method in swift same like objective C, with better ways
Here I have added code with getter method for one time allocation in obj c. 在这里,我在obj c中使用getter方法添加了一次分配代码。 How we will write same code in swift. 我们将如何快速编写相同的代码。 I need one time allocation. 我需要一次分配。 I already seen the computed get and set method, but can't find a solution for this. 我已经看过计算的get和set方法,但是找不到解决方案。
@property (nonatomic, strong) UIImageView *bgImageView;
- (UIImageView *)bgImageView{
if (_bgImageView == nil) {
_bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, width, 277)];
_bgImageView.image = [UIImage imageNamed:@"imageName"];
_bgImageView.alpha = 0;
_bgImageView.backgroundColor = [UIColor colorWithHexString:@"f4f4f4"];
}
return _bgImageView;
}
[self.view addSubview:self.bgImageView];
Swift introduced a new concept, lazy property. Swift引入了一个新概念,即惰性属性。 A lazy property is initialized only when you use it for the first time. 仅当您第一次使用惰性属性时,才初始化它。 Like a custom getter in objective-C, you can also add some logic after creating the object (for example, in your case, setting alpha value, image, and background color) 像Objective-C中的自定义吸气剂一样,您还可以在创建对象后添加一些逻辑(例如,在您的情况下,设置alpha值,图像和背景色)
lazy var bgImageView:UIImageView = {
var imageView = UIImageView(frame: CGRectMake(0, 0, width, 27))
imageView.image = UIImage(named: "imageName")
imageView.alpha = 0
imageView.backgroundColor = UIColor(red: 244/255, green: 244/255, blue: 244/255, alpha: 1)
return imageView
}()
The code is called only once, but Apple warns about multithreading access : 该代码仅被调用一次,但是Apple警告有关多线程访问:
If a property marked with the lazy modifier is accessed by multiple threads simultaneously and the property has not yet been initialized, there is no guarantee that the property will be initialized only once. 如果多个线程同时访问了标记有lazy修饰符的属性,并且该属性尚未初始化,则不能保证该属性仅被初始化一次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.