Objective-C中的受保护方法

LK.*_*LK. 110 objective-c

Objective-C中受保护方法的等价物是什么?我想定义只有派生类可以调用/实现的方法.

Bri*_*hal 155

您可以通过执行以下操作来模拟对方法的受保护和私有访问:

  • 在类扩展中声明您的私有方法(即在类.m文件顶部附近声明的未命名类别)
  • 在Subclass标头中声明受保护的方法 - Apple对UIGestureRecognizer使用此模式(请参阅UIGestureRecognizerSubclass.h的文档和参考)

正如Sachin指出的那样,这些保护并不是在运行时强制执行的(例如,它们在Java中).

  • +1,但我想强调**模拟**. (22认同)
  • 您好yonix,子类标头的导入将在.m文件内部完成,而不是在.h文件内部,因此导入子类将不会导入这些受保护的方法. (5认同)
  • 感谢您指出Apple如何在内部完成它.我[发布了一个完整的例子](http://bootstragram.com/blog/simulating-protected-modifier-with-objective-c/)如何实现东西,就像Apple在`UIGestureRecognizerSubclass.h`中所做的那样. (5认同)
  • 关于类似UIGestureRecognizer的解决方案:问题是,如果某些代码导入子类,它还将导入Subclass标头,因此它可以访问"protected"方法.有办法吗? (2认同)

Sac*_*hag 46

你既不能申报的方法保护私人.Objective-C的动态特性使得无法实现方法的访问控制.(你可以通过大量修改编译器或运行时,以严重的速度惩罚来做到这一点,但是由于显而易见的原因,这没有完成.)

取自Source.


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)

  • *protected* 的意思是**不能**被外部调用。您仍然可以调用类中定义的任何方法,而不管它们是否在外部可见。 (2认同)

小智 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)

  • 在这种情况下,编译器仍然会对未实现的方法`protectedMethod`发出警告 (2认同)