作为一个Java背景的开发者,在Objective-C中编写防御性程序有些困难。
假设SomeClass是可变的并且提供了一个copy方法,下面是我在Java中会编写的典型代码:
public MyClass
{
private SomeClass customerList;
...
public SomeClass getCustomerList() {
return this.customerList.copy();
}
public void setCustomerList(SomeClass list) {
this.customerList = list.copy();
}
}
我花了一些时间才弄清楚
@property (nonatomic, copy) SomeClass *customerList;
在将参数分配给customerList属性之前,会复制setter的参数。让我困惑的是编写一个合适的getter。目前看起来是这样的:
(SomeClass *)customerList {
if(!_customerList) {
_customerList = [[SomeClass alloc] init];
}
return _customerList;
}
这种方法适用于所有内部方法调用,例如self.customerList = ...,但对于创建安全漏洞的任何外部调用都会传递直接指针。我正在考虑提供一个不同的公共getter来返回副本,但希望避免这样做,因为它需要有一个非传统的名称。您会如何处理这种情况?
谢谢。
autorelease
。编辑:经过思考,我认为ARC会为你插入autorelease
,但我不是完全确定... - Carl Veazey