Copying an immutable string?

In the BNR iOS book, authors say to make this copy instead of strong :

 @property (nonatomic, copy) NSString *itemName; 

But I don’t quite understand the purpose, because in the main method I tried:

 BNRItem *calculator = [[BNRItem alloc] init]; NSString *pickle = @"pickbarn"; backpack.itemName = pickle; pickle = @"fuffle"; 

When I printed the name of the backpack on the console, it was picklebarn , so I don’t understand why itemName should be copied ?

+4
source share
4 answers

Since it is possible that the transmitted string may be transmitted.

(In addition, IIRC, -copy on an immutable line just saves it under the hood.)

+5
source

As Veva said; you don’t know if the string is changed, modified or not. The following backpack.itemName example will turn out to be "fuffle" if you are not copying:

 BNRItem *calculator = [[BNRItem alloc] init]; NSMutableString *pickle = [[NSMutableString alloc] initWithString:@"pickbarn"]; backpack.itemName = pickle; [pickle setString:@"fuffle"]; 
+4
source

I also studied the book you mentioned and the program you wrote above.

COPY is used when you are dealing with objects that change. You can use COPY to get the value of an object at a specific moment and at that particular moment, this value does not depend on changes made by other owners of the object.

+3
source
  NSString *pickle = @"pickbarn"; 

pickle is a pointer. It points to an NSString in memory.

  backpack.itemName = pickle; 

now your backpack property itemName points to the same NSString in memory.

  pickle = @"fuffle"; 

pickle now points to a new NSString in memory. But we did not change the backpack property itemName. It still points to @"pickbarn" in memory.

This will work just like the attribute of your strong or copy property.

If you want to know more about attributes ( copy , strong ), check out this thread .

+1
source

Source: https://habr.com/ru/post/1479268/


All Articles