向子类公开私有的 Objective-C 方法或属性 [英] Expose a private Objective-C method or property to subclasses
问题描述
根据一些官方讨论,Objective-C 中的类应该只在其头中公开公共方法和属性:
According to some official talk, a class in Objective-C should only expose public methods and properties in its header:
@interface MyClass : NSObject
@property (nonatomic, strong) MyPublicObject *publicObject;
- (void)publicMethod;
@end
和私有方法/属性应保存在 .m 文件中的类扩展名中:
and private methods/properties should be kept in class extension in .m file:
@interface MyClass()
@property (nonatomic, strong) MyPrivateObject *privateObject;
- (void) privateMethod;
@end
而且我认为对于私有但可从子类访问的事物没有 protected
类型.我想知道,除了公开声明私有属性/方法之外,还有什么方法可以实现这一点吗?
and I don't think there is a protected
type for things that are private but accessible from subclasses. I wonder, is there anyway to achieve this, apart from declaring private properties/methods publicly?
推荐答案
解决这个问题的一种方法是在你的子类的类扩展中重新声明该属性,然后添加一个@dynamic
语句,以便编译器不会创建该属性的覆盖实现.所以就像:
One way to solve this is to re-declare the property in your subclass's class extension, and then add an @dynamic
statement so that the compiler won't create an overriding implementation of that property. So something like:
@interface SuperClass ()
@property (nonatomic, strong) id someProperty;
@end
....
@interface SubClass ()
@property (nonatomic, strong) id someProperty;
@end
@implementation SubClass
@dynamic someProperty;
@end
这显然不理想,因为它重复了一个私有可见的声明.但在某些情况下它非常方便和有用,所以我想说的是逐案评估这种复制所涉及的危险与在公共界面中公开属性.
This obviously isn't ideal because it duplicates a privately visible declaration. But it is quite convenient and helpful in some situations so I'd say evaluate on a case-by-case basis the dangers involved in this duplication vs. exposing the property in the public interface.
Apple 在 UIGestureRecognizer 中使用的另一种方法是在单独的类别头文件中声明属性,明确命名为私有"或受保护",例如SomeClass+Protected.h".这样,其他程序员就会知道他们不应该导入文件.但是,如果您不控制从其继承的代码,那将不是一种选择.
An alternative - that is used by Apple in UIGestureRecognizer - is to declare the property in a separate category header file explicitly named as "private" or "protected" e.g. "SomeClass+Protected.h". That way, other programmers will know they ought not import the file. But, if you don't control the code you're inheriting from, that's not an option.
这篇关于向子类公开私有的 Objective-C 方法或属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!