I am using ARC.
This is my .h file
...
- (id)initWithCoordinate:(CLLocationCoordinate2D)c title:(NSString *)t;
@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
@property (nonatomic, copy) NSString *title;
...
This is my .m file
....
@synthesize coordinate, title;
- (id)initWithCoordinate:(CLLocationCoordinate2D)c title:(NSString *)t
{
self = [super init];
if (self) {
coordinate = c;
[self setTitle:t];
}
return self;
}
....
-
Is setting coordinate this way, the right way to do it? Given that I declare it as
readonly, it seems like it is the only way to do it. What if I just use the default (i.e.readwrite), in this case, should I use the setter method [self setCoordinate] instead? -
I could set the title by doing
title = tas well. Compare to using the setter method, the result is the same, but what is the difference ?
Thanks! Wish I could accept all of your answers.
1: As your code is now, yes, that is the right way to do it. If you weren’t using ARC (assuming you are currently), you’d also want to retain the value to assert ownership. This will be done automatically under ARC. Keep in mind that that is not the only way of doing it; you could redeclare the property as
readwritein the class extension in the implementation file. This is a common practice which allows you to have the benefits of areadwriteproperty while having the property still bereadonlyto users of the class. Ex.At the end of the day, I’d say it’s a good habit to use setters whenever you can to keep things KVO compliant and so that you always know when values change. For instance, if you have a custom UIView with a property that is reflected in its appearance, chances are you’d want to redisplay yourself when it changes. The easiest way to do this is to implement the setter yourself and call
setNeedsDisplayafter setting the value. You couldn’t do that if you set the instance value backing the property directly; the user of the class would have to remember to callsetneedsDisplayevery time they set it, manually.2: One goes through the setter method, giving you a way to know when a value is going to be set, while one sets a value to the instance variable backing the property. The setter method will always handle memory management in the way it was told to, while it’s up to you to do things such as
copying values for acopysetter if you assign directly to an instance variable, so that you maintain some consistent scheme. Going through setters sometimes, and not others can lead to some nasty bugs if you don’t be careful. Never going through setters makes it hard to know when values change, making it near impossible to weed out invalid values. For instance, if you had anintproperty you wanted to limit to values in some range and someone passed in a value under the minimum limit, you’d probably want to set the property to the lowest possible value in the range. You can’t do that without the value going through the setter first.