简体   繁体   中英

iOS: When to assign & when to create new copy of objects being assigned to a property

(someone please edit the title, clearly I'm not great with lingo yet)

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

Now, inside my root view controller, where the completion block is defined, I want to store the NSData in a property NSData (strong,nonatomic) *responseData of the root view controller. My question is, in the callback should I be using

weakSelf.responseData = [NSData dataWithData:passedInData]; 

or can I simply use:

 weakSelf.responseData = passedInData;

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

A brief explanation of the right answer would be appreciated and help me to understand how memory is managed (I've done a bunch of reading, but a practical example/explanation would go a long way for me).

I would use a copy property:

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

A copy property is suggested when the property is a pointer to a class that has also a mutable subclass, to avoid circumstances when your object mutates without that you know. Suppose for instance that there is another class that holds a pointer to this data object, and that it's mutable. It may be changed by the other class without that you know.

You don't need to copy it if the property is readonly , and you are sure that it points to an immutable object. However sending a copy message to an immutable object isn't expensive: it returns the object itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM