3

Suppose I have properties

@property (readonly) NSString* p1;
@property (readonly, copy) NSString* p2;
@property (readonly, nonatomic) NSString* p3;

Is there any difference between them?

I am thinking there is no difference because the "copy" and the "nonatomic" will have no effect because the setter method does not exist.

Binarian
  • 12,296
  • 8
  • 53
  • 84
John Henckel
  • 10,274
  • 3
  • 79
  • 79
  • How do you know the setter doesn't exist? I often have setters that are not exported to the header file. And "copy" means you can be sure your string isn't mutable. – gnasher729 Jun 09 '14 at 16:34
  • @gnasher729 you're right. I didn't realize that the setter can be added outside the header, for instance using a category. – John Henckel Jun 09 '14 at 18:26

2 Answers2

1

There is a difference and it will affect how the generated getter behaves.

Something like this:

@property (readonly) NSString* p1;

- (NSString *)p1 {
    @synchronized(self) {
        return _p1;
    }
}

@property (readonly, copy) NSString* p2;

- (NSString *)p2 {
    @synchronized(self) {
        return [_p2 copy];
    }
}

@property (readonly, nonatomic) NSString* p3 {

- (NSString *)p3 {
    return _p3;
}
trojanfoe
  • 120,358
  • 21
  • 212
  • 242
  • 6
    I don't believe `copy` affects the getter, just a setter. `copy` will not be called when getting the property value. – rmaddy Jun 09 '14 at 16:08
  • @rmaddy Yeah you might be right; I had always assumed it affects both setter and getter but I cannot find anything to support that assumption. – trojanfoe Jun 09 '14 at 16:13
  • 1
    It also becomes relevant if you provide a private setter, the decorations have to match at that point. – David Berry Jun 09 '14 at 16:26
  • 1
    I'm also pretty sure copy only applies to the setter. Also, atomic doesn't necessarily lock the object--it just ensures that getters/setters on that property run exclusively. i.e. you can't execute the getter from thread B while thread A is still in the middle of the setter. cf. https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/EncapsulatingData/EncapsulatingData.html#//apple_ref/doc/uid/TP40011210-CH5-SW37 – nielsbot Jun 09 '14 at 16:45
0

Yes, they are different because a setter could be added using a category.

By the way, you should always specify copy for NSString properties.

Community
  • 1
  • 1
John Henckel
  • 10,274
  • 3
  • 79
  • 79