Bri*_*hal 155
您可以通过执行以下操作来模拟对方法的受保护和私有访问:
正如Sachin指出的那样,这些保护并不是在运行时强制执行的(例如,它们在Java中).
Mic*_*han 13
这是我为了让子类可见的受保护方法而做的,而不要求它们自己实现这些方法.这意味着我的子类中没有关于具有不完整实现的编译器警告.
SuperClassProtectedMethods.h(协议文件):
@protocol SuperClassProtectedMethods <NSObject>
- (void) protectMethod:(NSObject *)foo;
@end
@interface SuperClass (ProtectedMethods) < SuperClassProtectedMethods >
@end
Run Code Online (Sandbox Code Playgroud)
SuperClass.m :(编译器现在会强制你添加受保护的方法)
#import "SuperClassProtectedMethods.h"
@implementation SuperClass
- (void) protectedMethod:(NSObject *)foo {}
@end
Run Code Online (Sandbox Code Playgroud)
SubClass.m:
#import "SuperClassProtectedMethods.h"
// Subclass can now call the protected methods, but no external classes importing .h files will be able to see the protected methods.
Run Code Online (Sandbox Code Playgroud)
小智 9
我刚刚发现了这个并且它对我有用.为了改进Adam的答案,在你的超类中在.m文件中实现受保护的方法但不在.h文件中声明它.在您的子类中,使用超类的受保护方法的声明在.m文件中创建一个新类别,并且可以在子类中使用超类的受保护方法.如果在运行时强制,这不会最终阻止所谓的受保护方法的调用者.
/////// SuperClass.h
@interface SuperClass
@end
/////// SuperClass.m
@implementation SuperClass
- (void) protectedMethod
{}
@end
/////// SubClass.h
@interface SubClass : SuperClass
@end
/////// SubClass.m
@interface SubClass (Protected)
- (void) protectedMethod ;
@end
@implementation SubClass
- (void) callerOfProtectedMethod
{
[self protectedMethod] ; // this will not generate warning
}
@end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
54316 次 |
| 最近记录: |