1

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;
}
jscs
  • 63,694
  • 13
  • 151
  • 195
felix
  • 11,304
  • 13
  • 69
  • 95

2 Answers2

1

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.

jscs
  • 63,694
  • 13
  • 151
  • 195
  • 2
    It may be readonly or it may be re-declared as readwrite in an extension (which it appears not to be). But, yeah... dead-on. This is just inconsistent and poor coding style. Deleted my answer; yours is more comprehensive. – bbum Sep 09 '12 at 21:29
  • He could've made it readwrite in a private interface and readonly in the public interface. Only time I really make things completely readonly is if there isn't a variable directly backing up the property, but rather, it's a contrived way of handing out some other, hidden, internal state, or the return value is a sum of multiple state values, etc. There is an actual variable here which he sets... so why not make it readwrite privately and go through the setter? More consistent, since all he seems to want to do is prevent people from messing with _coordinate_ except through the initializer. – Metabble Sep 09 '12 at 22:07
0

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.

Community
  • 1
  • 1
FeifanZ
  • 16,250
  • 7
  • 45
  • 84