Person.m
@interface Person : NSObject
@property(nonatomic,copy)NSString *name;
@property(nonatomic,copy)NSString *sex;
-(void)changeNameValue:(NSString*)newName andsexvalue:(NSString*) sexvalue;
@end
-(void)changeNameValue:(NSString *)newName andsexvalue:(NSString *)sexvalue{
self.name=newName;
_sex=sexvalue;
}
controller.m
NSMutableString *newname=[NSMutableString stringWithFormat:@"tony"];
NSMutableString *newsex=[NSMutableString stringWithFormat:@"man"];
Person *xiaoming = [[Person alloc] init];
[xiaoming changeNameValue:newname andsexvalue:newsex];
NSLog(@"xiaoming newName: %@, newSex: %@;", xiaoming.name, xiaoming.sex);
[newname appendString:@"Good"];
[newsex appendString:@"andwoman"];
NSLog(@"To observe the changes : xiaoming name: %@, sex: %@;", xiaoming.name, xiaoming.sex);
结果如下:
Person中的方法self.使用的是深拷贝,_sex使用的是浅拷贝。当controller中newname添加新内容不会影响到其他类的属性,_sex的浅拷贝会随着调用该属性的变量一起改变。因为self.会生成getter与setter方法,_a并不会生成getter与setter方法。