iOS set 方法

来源:互联网 发布:ce录音软件好用吗 编辑:程序博客网 时间:2024/05/17 03:13

为了能让类的成员变量正确的被外接访问,我们需要设置set和get方法。

[objc] view plaincopy
  1. @property (nonatomic,retain)NSString *test1;  
  2. @property (nonatomic,copy)NSString *test2;  

成员变量的属性不同(retain,copy)相对于的set方法也不同:

[objc] view plaicop
  1. @implementation SecondViewController  
  2. - (void)setTest1:(NSString *)test//retain  
  3. {  
  4.     // test需要先retain一次,放在自赋值时test被释放为nil  
  5.     [test retain];  
  6.     if (_test1 != nil) {  
  7.         [_test1 release];  
  8.     }  
  9.     //直接release无需判断也是可以的,iOS中对nil进行release操作合法  
  10.     //[_test1 release];  
  11.     _test1 = test;  
  12. }  
  13. - (void)setTest2:(NSString *)test//copy  
  14. {  
  15.     if (_test2 != nil) {  
  16.         [_test2 release];  
  17.     }  
  18.     // 也可以不用判断  
  19.     // [_test2 release];  
  20.     _test2 = [test copy];  
  21. }  
0 0
原创粉丝点击