camdez.com

Rule #1: There are no rules.

Copy, Don't Retain NSString Properties

| Comments

In general, @properties of type NSString* should be copied, not retained:

1
2
3
4
5
@interface SomeClass : NSObject

@property (nonatomic, copy) NSString* someText;

@end

The reasoning behind this is that because NSString is a class cluster, what appears to be an NSString could really be an NSMutableString, and thus could change behind your back—generally not something you want. However, if you specify copy then the instance of SomeClass will have it’s own unique copy of the original string.

It’s also worth mentioning in passing that calling the copy method on a mutable object (NSMutableString, NSMutableArray, etc.) returns an immutable copy of the original object.

Comments