In the following example, does stringWithString:(NSString *) copy the memory address/location of theName to name or it actually copies the data from theName to name?
@interface AddressCard:NSObject
-(void)setName:(NSString *)theName;
@end
@implementation AddressCard
NSString *name;
-(void)setName:(NSString *)theName
{
if(name!=theName)
name = [NSString stringWithString:theName];
}
@end
If I change the code to following, what does copy do differently?
@interface AddressCard:NSObject
@property (copy, nonatomic) NSString *name;
@end
@implementation AddressCard
@synthesize name;
@end
In general, does copy (@property attribute) copy the address of the data or copies the data from one variable to another? If it is latter case, are we not consuming a lot of memory when the variable represents large data?
Thank you for your time and response!
+[NSString stringWithString:]will effectively ‘copy’ the string.It performs whatever the object considers is a
copy. It may return a new object, or it may return itself. For example,+[NSString stringWithString:]could just return the parameter retained and autoreleased if the parameter is already immutable. If the parameter is mutable, then it will return a new instance, so you are guaranteed to have an immutable instance.Aha – but that’s the trick! Yes, you could end up making many new allocations with copy, but the trick is often that copies of reference counted objects are truly very shallow in most cases when you favor immutable types and using
copy. Many collections types can simply return themselves if they are already immutable, or their ivars may do so, so it’s actually a really good idea to ensure you are not passing around mutable objects — so creating an immutable copy early really allows this optimization to propagate, and saves you a ton of allocations (but not always — there are a number of corner cases for all these variants).Note: Not all classes distinguish immutability from mutability, so a copy does not always return an immutable object.