DevPrep

All topics › Objective-C

When is it better to use copy for NSString, and why?

Middle PRO

Essence

NSString is part of a class cluster with a mutable subclass NSMutableString. Thanks to polymorphism you can assign an NSMutableString to a property of type NSString *, and if the property is strong you store a pointer to someone else's mutable object: the owner edits the string — and "your" value changes too. copy in the setter takes an immutable snapshot, so the property behaves like a value, not a reference.

#import <Foundation/Foundation.h>

@interface User : NSObject
@property (nonatomic, strong) NSString *nickStrong;
@property (nonatomic, copy)   NSString *nickCopy;
@end
@implementation User
@end

static void demo(void) {
    NSMutableString *draft = [NSMutableString stringWithString:@"ann"];
    User *u = [User new];
    u.nickStrong = draft;
    u.nickCopy = draft;
    [draft appendString:@"_2026"];
    NSLog(@"%@ / %@", u.nickStrong, u.nickCopy); // ann_2026 / ann
}

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store