OC中self.a与_a的用法

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);

结果如下:
OC中self.a与_a的用法

Person中的方法self.使用的是深拷贝,_sex使用的是浅拷贝。当controller中newname添加新内容不会影响到其他类的属性,_sex的浅拷贝会随着调用该属性的变量一起改变。因为self.会生成getter与setter方法,_a并不会生成getter与setter方法。

上一篇:js基础(1)


下一篇:python之dict