Objective-C NSString: Why use copy instead of strong,
Objective-C NSString: Why do we need to modify it with copy instead of strong?
See the following code:
@interface ViewController ()@property (nonatomic, strong) NSString *strStrong;@property (nonatomic, copy) NSString *strCopy;@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. NSMutableString *mutableString = [NSMutableString stringWithString:@"hello"]; self.strStrong = mutableString; self.strCopy = mutableString; NSLog(@"strStrong:%@",self.strStrong); NSLog(@"strCopy:%@",self.strCopy); [mutableString appendString:@" world"]; NSLog(@"strStrong:%@",self.strStrong); NSLog(@"strCopy:%@",self.strCopy);}
First, let's take a look at what information the producer will output.
View the result
StringStrongOrCopy[36258:1045977] strStrong:helloStringStrongOrCopy[36258:1045977] strCopy:helloStringStrongOrCopy[36258:1045977] strStrong:hello worldStringStrongOrCopy[36258:1045977] strCopy:hello
Do you understand?
If you do not want the NSString value to be modified, using copy will prevent you from accidentally modifying the NSString value.