在Objective-C中完成受保护属性的解决方法 [英] Workaround to accomplish protected properties in Objective-C

查看:104
本文介绍了在Objective-C中完成受保护属性的解决方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图找到一种解决方法,以便在Objective-C中声明@protected属性,以便只有层次结构中的子类才能访问它们(只读,而不是写). 我读到没有任何记录的方法可以做到这一点,所以我想到了这种解决方法,我想问一下StackOverflow对此的看法.

I've been trying to find a workaround to declare @protected properties in Objective-C so only subclasses in the hierarchy can access them (read only, not write). I read that there is no documented way of doing this so I thought of this workaround and I wanted to ask StackOverflow's opinion about it.

层次结构顶部的每个自定义类都包含三个类,一个实现和两个接口. 我们为其命名:

Every custom class at the top of the hierarchy contains three classes, one implementation and two interfaces. Let's name them:

ClassA.h
ClassA_protected.h
ClassA.m

那么该ClassA的任何子类将照常:

Then any subclass of this ClassA would be as usual:

ClassB.h
ClassB.m

首先,我创建了接口 ClassA.h ,在该接口中声明了一个受保护的int变量,以便ClassA的任何子类都可以访问它:

First I created the interface ClassA.h where I declare a protected int variable so any subclass of ClassA can have access to it:

@interface ClassA : NSObject{
    @protected
    int _myProtectedInt;
}
@end

下一步是我正在讨论的解决方法.但是,一旦阅读它,就会发现它很简单.我声明了另一个名为 ClassA_protected.h 的接口,它实际上是ClassA.h的扩展,并允许我们将该属性标记为readonly:

Next step is the workaround I was talking about. However, once you read it you will see that it is quite straight forward. I declared a second interface called ClassA_protected.h which actually works as an extension of ClassA.h and allows us to tag the property as readonly:

#import "ClassA.h"
@interface ClassA ()
@property (nonatomic , readonly) int myProtectedInt;
@end

准备受保护的层次结构的最后一步是在 ClassA.m 中声明其实现,在此我们仅合成属性:

Last step of preparing the protected hierarchy is to declare its implementation in ClassA.m where we only synthesize our property:

#import "ClassA_protected.h"
@implementation ClassA
@synthesize myProtectedInt = _ myProtectedInt;
@end

这样,每个需要成为 ClassA.h 子类的类都将导入 ClassA_protected.h .这样的孩子,例如 ClassB.h ,如下所示:

This way, every class that needs to be a subclass of ClassA.h, will import ClassA_protected.h instead. So a child like, for example ClassB.h, would be as follows:

#import "ClassA_protected.h"
@interface ClassB : ClassA
@end

以及从 ClassB.m 的实现访问此属性的示例:

And an example of accessing this property from ClassB.m's implementation:

@implementation ClassB
-(void) method {
    //edit protected variable 
    _myProtectedInt= 1;

    //normal access
    self.muProtectedInt;
}
@end

推荐答案

当然可以. Apple在UIGestureRecognizer类中使用了相同的方法.子类必须导入其他UIGestureRecognizerSubclass.h文件并覆盖该文件中声明的方法.

Sure, that works fine. Apple uses the same approach for example in the UIGestureRecognizer class. Subclasses have to import the additional UIGestureRecognizerSubclass.h file and override the methods that are declared in that file.

这篇关于在Objective-C中完成受保护属性的解决方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆