NSString为何要用COPY属性
copy The copy option makes a copy of an object and then changes the pointer to refer to this copy.
copy属性将制造一个传入对象的副本并且将指针指向这个新副本。
@property (copy) NSString *lastName;
此时生成的setter方法应该是
- (void)setLastName:(NSString *)d { lastName = [d copy]; }
类似这样。
// Create a mutable string NSMutableString *x = [[NSMutableString alloc] initWithString:@"Ono"]; // Pass it to setLastName: [myObj setLastName:x]; // 'copy' prevents this from changing the lastName [x appendString:@" Lennon"];
此时你将x传给setLastName:方法后,lastName指向的对象并不是x,而是x的副本,此时x属性发生改变并不会对lastName造成影响,是一种切断关联的拷贝方式。copy保证了内容不会意外改变。