IOS: when to assign and when to create a new copy of objects assigned to a property

(someone, please edit the name, it is clear that I am not very good with jargon)

So, let's say I have an object called DataRequester whose task is to create an NSURLConnection , as well as its delegate. I instantiate an object from my root view controller, and also provide a callback block (which is a DataRequester property). When the NSURLConnection finished loading, I call the callback and pass in the NSData as a parameter.

Now, in my root view controller where the completion block is defined, I want to save the NSData in the NSData (strong,nonatomic) *responseData property of the root view controller. My question is: in the callback should I use

 weakSelf.responseData = [NSData dataWithData:passedInData]; 

or I can just use:

  weakSelf.responseData = passedInData; 

(Where RootViewController * __weak weakSelf = self) Also, the project uses ARC.

A brief explanation of the correct answer would be appreciated and would help me understand how memory is managed (I did a bunch of reading, but a practical example / explanation would come a long way for me).

+4
source share
1 answer

I would use the copy property:

 NSData (copy,nonatomic) *responseData; // Then weakSelf.responseData = passedInData; 
Property

A copy suggested when a property is a pointer to a class that also has a mutable subclass to avoid circumstances when your object mutates without your knowledge. Suppose, for example, that there is another class that contains a pointer to this data object and that it is modified. It can be changed by another class if you do not know this.

You do not need to copy it if the property is readonly , and you are sure that it points to an immutable object. However, sending a copy of the message to an immutable object is small: it returns the object itself.

0
source

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


All Articles