What is necessary to use copy

in .h file we declared

in .m file we declared

-(instancetype)initWithProductName:(NSString *)pn;
    //Call NSObject's init method
    self = [super init];
    //Did it return something non-nil?
        //Set the product name
        _productName = [pn copy];
        //Give the voltage a starting value
        _voltage = 120;
    return self;

Was copy attributes really necessary in the property, why don’t we just assign the argument of the parameter pn directly to _productName?

We declared productName to be a copy property. This means that any time we use the setter “self.productName = @“Something”” or its equivalent “[self setProductName:@“Something”]”, our _productName instance variable will be made to point to a /copy/ of the passed-in string, rather than the passed-in string itself.

In our init method, however, we are not using the setter for the productName property, and so the copy will not be automatically made. We must make it manually by setting the instance variable to a copy of the passed-in variable.

so are you trying to say that using Copy or using setter or self.productName produce the same result.
If so wouldn’t it be better to just use self.productName reduce the line of code that way.


Let me try to break apart your questions to make things a bit more clear.

Why declaring productName to be a copy property.

Under the above condition, no matter we are using “self.productName = @“Something”” or its equivalent "[self setProductName:@“Something”], we can ensure that when calling the setter method, it will do what we expect, the instance variable will point to a “copy”.

Why not using the setter method to initialize _productName within the init method?
In Chapter 33.init – Using accessors, it discuss that whether we should use the accessors methods in our init method. At Big Nerd Ranch, they tend to directly set the instance variables within init methods.

I am just a beginner, my explanation could be incorrect or in accurate. It’d be nice to have correction if I am wrong.