Reputation: 11552
I took this code from the Big Nerd Ranch iOS Programming book. In the code, they are assigning two instance variables, coordinate
and title
. Why is coordinate
assigned directly, and title
is set by calling a setter?
Header File
@interface BNRMapPoint : NSObject<MKAnnotation>
-(id)initWithCoordinate:(CLLocationCoordinate2D )c title:(NSString *)t;
@property(nonatomic, readonly) CLLocationCoordinate2D coordinate;
@property(nonatomic, copy) NSString *title;
@end
Implementation File
-(id)initWithCoordinate:(CLLocationCoordinate2D)c title:(NSString *)t
{
self = [super init];
if(self){
coordinate = c;
[self setTitle:t];
}
return self;
}
Upvotes: 1
Views: 131
Reputation: 16316
There is a school of thought that says you should copy NSStrings. They're invoking the setter on the string to get that copy. However, there's no need to copy (or even retain) the coordinate, as Josh points out.
Upvotes: 0
Reputation: 64002
Two reasons, the most important of which is that there is no setter for the coordinate
property. It's declared read-only, so there is only a getter method generated.
The second is that CLLocationCoordinate2D
is a struct, not an object. There are memory management actions (copying, in this case) that have to be taken for the title
object; the simplest way to make that happen is to use the already-existent setter method. The compiler takes care of moving the data for a POD type like CLLocationCoordinate2D
.
If the second were the only reason, however, this would be a poor decision -- that's bad style to use the setter for one property and not for the other.
Upvotes: 1