【发布时间】:2014-08-02 09:28:59
【问题描述】:
我正在尝试实现这个目标-c 代码
@property (strong) UIView *customView;
-(UIView*)customView
{
if (!customView){
self.customView = [[UIView alloc]init];
self.customView.backgroundColor = [UIColor blueColor];
}
return customView;
}
我为什么要用这个? customView 从很多地方调用,所以我们必须在所有地方检查这个条件。为了避免这种重复,我写了这个。
所以我尝试创建存储属性并使用 getter 方法检查是否已经创建。
var mainView : UIView? {
get{
if let customView = self.mainView{
return self.mainView
}
var customView : UIView = UIView()
self.mainView = customView
self.mainView.backgroundColor = UIColor(blueColor)
return customView
}
set{
self.mainView = newValue
}
}
这是正确的吗?或任何其他方法来做到这一点?
注意:上面的代码没有警告或错误。但是与存储和计算属性混淆。请让我清楚。
【问题讨论】: