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方法。