我从Big Nerd Ranch iOS编程书中获取了这段代码。在代码中,他们分配了两个实例变量coordinate
和title
。为什么直接分配coordinate
,并通过调用setter来设置title
?
标题文件
@interface BNRMapPoint : NSObject<MKAnnotation>
-(id)initWithCoordinate:(CLLocationCoordinate2D )c title:(NSString *)t;
@property(nonatomic, readonly) CLLocationCoordinate2D coordinate;
@property(nonatomic, copy) NSString *title;
@end
实施档案
-(id)initWithCoordinate:(CLLocationCoordinate2D)c title:(NSString *)t
{
self = [super init];
if(self){
coordinate = c;
[self setTitle:t];
}
return self;
}
答案 0 :(得分:1)
有两个原因,其中最重要的原因是coordinate
属性没有setter。它被声明为只读,因此只生成一个getter方法。
第二个是CLLocationCoordinate2D
是一个结构,而不是一个对象。存在必须为title
对象采取的内存管理操作(在这种情况下为复制);实现这一目标的最简单方法是使用已存在的setter方法。编译器负责移动POD类型的数据,如CLLocationCoordinate2D
。
如果第二个是唯一的原因,那么这将是一个糟糕的决定 - 对于一个属性而不是另一个属性使用setter是不好的方式。
答案 1 :(得分:0)
There is a school of thought说你应该复制NSStrings。他们在字符串上调用setter来获取该副本。但是,正如Josh指出的那样,没有必要复制(甚至保留)坐标。