Private methods using Categories in Objective-C: calling super from a subclass
我正在阅读如何在Objective-C中实现私有方法(在Objective-C中为类定义私有方法的最佳方法),我想到了一个问题:
如何实现受保护的方法,即子类可见的私有方法?
假设我有一个mysuperclass,它有一个包含它所有私有方法的类别,我想实现一个mysuperclass重写或调用其中一个mysuperclass私有方法的super。这是可能的吗(使用类别方法来实现私有方法)?
看看这些代码中的一些,底部是overriden方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | // =========================== // = File: MySuperClass.h // = Interface for MySuperClass // =========================== @interface MySuperClass : Object ... @end // =========================== // = File: MySuperClass.m // =========================== #import"MySuperClass.h" // ================================= // = Interface for Private methods // ================================= @interface MySuperClass (Private) -(void) privateInstanceMethod; @end // ===================================== // = Implementation of Private methods // ===================================== @implementation MySuperClass (Private) -(void) privateInstanceMethod { //Do something } @end // ================================ // = Implementation for MySuperClass // ================================ @implementation MySuperClass ... @end // =========================== // = File: MySubClass.h // = Interface for MySubClass // =========================== @interface MySubClass : MySuperClass ... @end // ================================ // = Implementation for MySubClass // ================================ #import MySubClass.h @implementation MySubClass //OVERRIDING a Super Private method. -(void) privateInstanceMethod { [super privateInstanceMethod]; //Compiler error, privateInstanceMethod not visible! //Do something else } @end |
希望有人已经知道了。
干杯!
在苹果,当他们构建框架时,典型的模式是拥有一个公共头(myclass.h)和一个私有头(myclass_private.h),并且只将公共头复制到构建产品中。当然,.m文件会同时导入这两个文件。
gnustep页面介绍了一种方法,第4.5节:
...The bright side of this is it
allows you to simulate protected
methods as well. For this, the writer
of a subclass must be informed in some
way about the protected methods, and
they will need to put up with the
compiler warnings. Alternatively, you
could declare the Protected category
in a separate interface file (e.g.,
"PointProtected.h"), and provide this
interface file with the understanding
that it should only be imported and
used by a subclass's interface file.