Use copy for NSString properties

When you declare a NSString property it is best to use copy instead of strong. In fact this is true for any immutable class that conforms to the NSCopying protocol like NSNumber, NSArray, NSSet and others. All these classes I mentioned also have a mutable version. You want to use copy because your NSString property can be passed either a NSString or a NSMutableString instance. If you’re being passed a NSMutableString instance then that means the value of your string may change behind your back. Let’s consider this example:

@interface Book : NSObject

@property (strong, nonatomic) NSString *title;

@end

 

In another class we have this method:

- (void)stringExample {

    NSMutableString *bookTitle = [NSMutableString stringWithString:@"Best book ever"];

    Book *book = [[Book alloc] init];

    book.title = bookTitle;

    [bookTitle setString:@"Worst book ever"];

    NSLog(@"book title %@", book.title);

}

When we run this we notice that the title of our book is now “Worst book ever”. If instead of declaring the property strong we use copy then the title of our book will be “Best book ever” as you would probably expect. In the first case, when we declare the property strong, the retain count for the string will increase by 1, but our property will point to the same memory address. This means that the value can be changed by anyone holding a reference to that memory address, in our case the bookTitle variable. If instead of strong we use copy then a new copy of that string will be created for our Book class. This means that modifying booTitle won’t have any effect on our string value and this is what we would want in most cases.

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *

*