@private、@protected、@public、@package关键字的使用和区别

@private: 私有的 只有自己可以使用,子类也不可以使用
@protected: 受保护的 自己可以使用,子类也可以使用
@public: 公共的 只要拿到这个类的对象,就可以使用该词修饰的变量
@package: 包 这个主要是用于框架类,使用@private太限制,使用@protected或者@public又太开放,就使用这个package

示例:

// 父类TestView
@interface TestView: UIView
{
  @private   NSString *privateStr;
  @protected NSString *protectedStr;
  @public    NSString *publicStr;
  @package   NSString *packageStr;
}
@end
@implementation
- (instancetype)initWithFrame:(CGRect)frame {
  if (self = [super initWithFrame:frame]) {
    privateStr = @"private";
    protectedStr = @"protected";
    publicStr = @"public";
    packageStr = @"package";
  }
}
@end
// 子类TestSubView
@interface TestSubView: TestView
@end
@implementation
- (instancetype)initWithFrame:(CGRect)frame {
  if (self = [super initWithFrame:frame]) {
    privateStr = @"privateSub";            // 这里会报错,因为私有的只有类本身可以使用,子类不能使用
    protectedStr = @"protectedSub"; 
    publicStr = @"publicSub";
    packageStr = @"packageSub";
  }
}
@end
// 其他类
@interface OtherView: UIView
@end
@implementation
- (instancetype)initWithFrame:(CGRect)frame {
  if (self = [super initWithFrame:frame]) {
    TestView *testView = [[TestView alloc] initWithFrame:self.bounds];
    testView->privateStr  = @"privateOther";     // 这里会报错
    testView->protectedStr = @"protectedOther";  // 这里会报错
    testView->publicStr = @"publicOther";
    testView->packageStr = @"packageOther";
    [self addSubView:testView];
  }
}
@end
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 参考链接理解 Objective-C 中的指定构造方法 - 简书 问题1:NS_DESIGNATED_INITIA...
    lixiaoshuai阅读 2,484评论 0 0
  • 1.设计模式是什么? 你知道哪些设计模式,并简要叙述?设计模式是一种编码经验,就是用比较成熟的逻辑去处理某一种类型...
    龍飝阅读 2,219评论 0 12
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,160评论 1 32
  • 设计模式是什么? 你知道哪些设计模式,并简要叙述? 设计模式是一种编码经验,就是用比较成熟的逻辑去处理某一种类型的...
    不懂后悔阅读 839评论 0 53
  • 设计模式是什么? 你知道哪些设计模式,并简要叙述? 设计模式是一种编码经验,就是用比较成熟的逻辑去处理某一种类型的...
    琦均煞Sylar阅读 434评论 0 0