首页 > 技术文章 > @private、@protected与@public三者之间的区别

YouXianMing 2015-09-15 20:21 原文

@private、@protected与@public三者之间的区别

 

类之间关系图

 

@private只能够使用在声明的类当中,其子类也不能够使用用@private声明的实例变量

 

@protected只能在声明的类当中使用,但其子类具有使用@protected声明变量的资格

 

@public可以全局使用,属性是具有全局属性的

 

实例变量其实是支持KVO的,如果你帮实例变量写了setter,getter方法

 

相关源码

#import <UIKit/UIKit.h>

@interface TitleView : UIView {

@private
    int        _count;    // 只能在当前类中使用
    
@protected
    NSString  *_title;    // 当前类与子类可以使用
    
@public
    NSString  *_subTitle; // 任何地方都可以使用
}

@property (nonatomic, strong) NSString  *info;

@end
#import "TitleView.h"

@implementation TitleView

- (instancetype)initWithFrame:(CGRect)frame {
    
    self = [super initWithFrame:frame];
    if (self) {
        
        _count = 4;
        
        _title = @"Title";
        
        _subTitle = @"SubTitle";
    }
    
    return self;
}

@end
#import "TitleView.h"

// MoreTitleView 继承自 TitleView
@interface MoreTitleView : TitleView

@end
#import "MoreTitleView.h"

@implementation MoreTitleView

- (instancetype)initWithFrame:(CGRect)frame {
    
    self = [super initWithFrame:frame];
    if (self) {
        
    }
    
    return self;
}

@end

 

即时没有写setter,getter方法,也是可以使用KVO的哦,只需要自己手动触发即可

推荐阅读