美文网首页runtime.runloop
@synthesize 的作用

@synthesize 的作用

作者: ImmortalSummer | 来源:发表于2021-03-16 11:06 被阅读0次
    @synthesize propertyName = _propertyName;
    

    使用@synthesize 只有一个目的——给实例变量起个别名,或者说为同一个变量添加两个名字。

    使用场景1: 为一个属性同时添加getter和setter方法

    @interface AsyncRequestViewController ()
    @property(nonatomic,strong) NSString *message;
    @end
    
    @implementation AsyncRequestViewController
    
    // 给message属性同时增加setter和getter方法编译会报错:
    // Use of undeclared identifier '_message';
    // 增加别名可以解决
    @synthesize message = _message;
    
    - (void)setMessage:(NSString *)message{
        _message = message;
    }
    
    - (NSString *)message{
        return [_message stringByAppendingString:@"!!!"];
    }
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        self.message = @"hello";
        NSLog(@"%@",self.message);  //打印结果: hello!!!
    }
    @end
    

    使用场景2:为一个只读属性添加setter方法

    @interface AsyncRequestViewController ()
    @property(nonatomic,strong,readonly) NSString *tip;
    @end
    
    @implementation AsyncRequestViewController
    
    // 给只读属性增加别名, 可以实现该只读属性的setter方法
    @synthesize tip = _tip;
    
    - (void)setTip:(NSString *)tip{
        _tip = tip;
    }
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        self.tip = @"666";
        NSLog(@"%@",self.tip);  //打印结果: 666
    }
    @end
    

    相关文章

      网友评论

        本文标题:@synthesize 的作用

        本文链接:https://www.haomeiwen.com/subject/vpnrcltx.html