سؤال

Should I have to manually copy object in custom setter with copy property in objective-c? For example,

I have a property:

@property (copy, nonatomic) NSString *someString;

and custom setter:

- (void)setSomeString:(NSString *)someString
{
  //option 1
  _someString = someString;
  //option 2
  _someString = [someString copy];
  //do other stuff
}

Is it option 1 enough for custom setter or I have to use option 2 instead in order to have copied object?

هل كانت مفيدة؟

المحلول

You can do whatever you like but you should use the second option. This is because it will be something like code documentation if other developer see it he or she will know that you copy the string just by looking at:

@property (copy, nonatomic) NSString *someString;

The same if you use retain/assign it's best practice to retain/assign object in custom setter. It will make your code more clearer more documented and much more understandable for others developers.

نصائح أخرى

You Must use "option 2" because you are using "copy" for your property and statement :

_someString = [someString copy];

would create a new object in memory and assign it to your property object.

If you write your own custom setter, then you are 100% responsible for everything it does. In your case, you are 100% responsible for the bug that you introduce with option 1 of your code: If I set someObject.someString to a mutable string and change the string later, then the string in your object will change which is most definitely not what you expect from a copy property.

In addition, if you have both a custom setter and getter (or a custom getter for a read-only property) so there is no compiler generated getter or setter, the compiler doesn't create the instance variable for you; you'll have to do that yourself.

You should also notice that "copy" of immutable objects doesn't actually copy them but just retains them, so usually the "copy" operation is really cheap, and when I pass a mutable object, "copy" was most likely what you wanted anyway.

Go with option 2 if you want to make own setter but don't forget to add the condition before the statement like...

if(_someString) {
    [_someString release]; 
}

Note:- In case of ARC use statement "_someString = nil" instead of "[_someString release]";

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top