views:

17

answers:

1

The docs say:

The default implementation does not copy attribute values. If the attribute value may be mutable and implements the NSCopying protocol (as is the case with NSString, for example), you can copy the value in a custom accessor to help preserve encapsulation (for example, in the case where an instance of NSMutableString is passed as a value).

So instead of getting into trouble and inconvenience with overwriting accessors in my NSManagedObject subclass, couldn't I simply do something like this?

myManagedObject.firstName = [[firstNameMutableStr copy] autorelease];

This would have the exact same effect, or not? The dynamic implementation would retain that anyways ... so.... why not the easy way?

+1  A: 

It's an open question whether having to remember to copy the mutable string every where in code you set the attribute is "the easy way."

With a custom accessor, you just write the copy once then forget about. It copies automatically from that point on.

Just imagine that in thousands of lines of code you forgot to copy just once and developed a subtle bug because that one attribute of the managed object sporadically changed because some other totally unrelated code subsequently changed the mutable string you held only by reference.

I could tell you some stories of weekends lost to debugging because someone took "the easy way."

TechZen
I see... indeed I remember similar situations like you've described. Correct me if I'm wrong: I can't just set the property declaration to "copy", and I can't just overwrite an setter and let it call -super (because of the dynamic nature), right? I must really completely write the setter on my own - but Xcode can help me with copying the accessors to clipboard. Is that right, so far?
dontWatchMyProfile
Yes, but I wouldn't worry about unless you know it will cause a problem. The example given is a poor one. In principle you would have to write a custom accessor for every string attribute to protect against the possibility it would be passed a mutable string. In reality, this is never a problem. The class cluster behind NSString, NSArray etc take care of all that for you. If you set a NSString attribute to a mutable string you end up with a static string.
TechZen