Answers:
您不能将方法声明为保护方法或私有方法。Objective-C的动态性质使其无法实现方法的访问控制。(您可以通过严重修改编译器或运行时来实现此目的,但速度会受到严重影响,但是出于明显的原因,这样做并未完成。)
取自Source。
您可以通过执行以下操作来模拟对方法的受保护和私有访问:
正如Sachin指出的那样,这些保护不是在运行时强制执行的(例如,在Java中)。
UIGestureRecognizerSubclass.h
这是我使子类可见的受保护方法的工作,而无需他们自己实现这些方法。这意味着我没有在子类中收到有关实现不完整的编译器警告。
SuperClassProtectedMethods.h(协议文件):
@protocol SuperClassProtectedMethods <NSObject>
- (void) protectMethod:(NSObject *)foo;
@end
@interface SuperClass (ProtectedMethods) < SuperClassProtectedMethods >
@end
SuperClass.m :(编译器现在将强制您添加受保护的方法)
#import "SuperClassProtectedMethods.h"
@implementation SuperClass
- (void) protectedMethod:(NSObject *)foo {}
@end
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.
performSelector使用它。
[(id)obj hiddenMethod]。准确地说,Objective-C不支持受保护的方法。
我只是发现了这一点,并且对我有用。要改进亚当的答案,请在您的超类中在.m文件中实现protected方法的实现,但不要在.h文件中声明它。在子类中,使用超类的protected方法的声明在.m文件中创建一个新类别,然后可以在子类中使用超类的protected方法。如果在运行时强制执行,这最终不会阻止所谓的受保护方法的调用者。
/////// 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
protectedMethod
使用@protected变量的另一种方法。
@interface SuperClass:NSObject{
@protected
SEL protectedMehodSelector;
}
- (void) hackIt;
@end
@implementation SuperClass
-(id)init{
self = [super init];
if(self) {
protectedMethodSelector = @selector(baseHandling);
}
return self;
}
- (void) baseHandling {
// execute your code here
}
-(void) hackIt {
[self performSelector: protectedMethodSelector];
}
@end
@interface SubClass:SuperClass
@end
@implementation SubClass
-(id)init{
self = [super init];
if(self) {
protectedMethodSelector = @selector(customHandling);
}
return self;
}
- (void) customHandling {
// execute your custom code here
}
@end
您可以使用类别进行此操作。
@interface SomeClass (Protected)
-(void)doMadProtectedThings;
@end
@implementation SomeClass (Protected)
- (void)doMadProtectedThings{
NSLog(@"As long as the .h isn't imported into a class of completely different family, these methods will never be seen. You have to import this header into the subclasses of the super instance though.");
}
@end
如果将类别导入另一个类中,则不会隐藏这些方法,但实际上不会。由于Objective-C的动态特性,无论调用实例的类型如何,实际上都不可能完全隐藏方法。
最好的方法可能是@Brian Westphal回答的类继续类,但是您必须为每个子类实例在此类中重新定义方法。
一种选择是使用类扩展来隐藏方法。
在.h:
@interface SomeAppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
在.m:
@interface SomeAppDelegate()
- (void)localMethod;
@end
@implementation SomeAppDelegate
- (void)localMethod
{
}
@end
@interface.m文件中的声明。您可以声明一个函数并使用它,它将被视为私有函数。