On Dec 22, 2008, at 4:04 PM, Debajit Adhikary wrote:

Let's say I have a class called SomeClass with a string property name:

@interface SomeClass : NSObject{
   NSString* name;
}

@property (nonatomic, retain) NSString* name;

@end

I understand that name may be assigned a NSMutableString in which case this
will may to errant behavior.

(1) For strings in general, is it *always* a good idea to use the "copy"
attribute instead of "retain"?

I would say that it is almost always proper to use the copy attribute for a string property. Merely "retain" means that the property is modeling a relationship rather than an attribute. There might be very rare cases where you want to have a relationship with a string, but I can't think of any off-hand.

(2) Is a "copied" attribute in any way less efficient than such a
"retain-ed" attribute?

For most of Cocoa's immutable value objects, -copy is equivalent to - retain (with perhaps one extra message dispatch). For mutable value objects, -copy makes real copy -- a new immutable object with the same value. This turns out to be exactly when you want a new object, because basing one of your attributes on a mutable string provided by somebody else opens you up to violations of encapsulation -- your object's attributes changing behind its back.

However, you should really stop yourself from thinking about what's less efficient until you see evidence of a performance problem and analyze the cause. It's a bad habit that will just cause you to waste effort and time.

Regards,
Ken

_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to