program story

Objective-C의 보호 된 메소드

inputbox 2020. 7. 30. 10:24
반응형

Objective-C의 보호 된 메소드


Objective-C에서 보호 된 메소드와 동등한 것은 무엇입니까? 파생 클래스 만 호출 / 구현할 수있는 메서드를 정의하고 싶습니다.


보호 된 메소드 또는 개인 메소드를 선언 할 수 없습니다 . Objective-C의 동적 특성으로 인해 메소드에 대한 액세스 제어를 구현할 수 없습니다. (심각한 속도 저하로 컴파일러 나 런타임을 크게 수정하여이를 수행 할 수 있지만 명백한 이유는 그렇지 않습니다.)

출처 에서 가져 왔습니다 .


다음을 수행하여 메소드에 대한 보호 및 개인 액세스를 시뮬레이션 할 수 있습니다 .

  • 클래스 확장에서 개인 메서드를 선언하십시오 (예 : 클래스의 .m 파일 맨 위에 선언 된 명명되지 않은 범주)
  • 서브 클래스 헤더에서 보호 된 메소드 선언 – Apple은 UIGestureRecognizer와 관련하여이 패턴을 사용합니다 (UIGestureRecognizerSubclass.h에 대한 문서 및 참조 참조)

Sachin이 지적한 것처럼 이러한 보호는 런타임에 시행되지 않습니다 (예 : Java와 같이).


다음은 메소드 자체를 구현하지 않고도 서브 클래스에 보호 된 메소드를 표시하기 위해 수행 한 작업입니다. 이것은 서브 클래스에서 불완전한 구현에 대한 컴파일러 경고를받지 않았다는 것을 의미했습니다.

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.

방금 이것을 발견하고 그것은 나를 위해 작동합니다 .Adam의 대답을 개선하기 위해, 수퍼 클래스에서 .m 파일로 보호 된 메소드를 구현하지만 .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

@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

메소드를 상위 클래스의 전용 메소드로 정의 [super performSelector:@selector(privateMethod)];하고 하위 클래스에서 사용할 수 있습니다 .


범주를 사용하여이 작업 수행 할 수 있습니다 .

@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

The methods aren't hidden if you import the category in another class, but you just don't. Due to the dynamic nature of Objective-C it's actually impossible to completely hide a method regardless of a calling instance type.

The best way to go is probably the class continuation category as answered by @Brian Westphal but you'll have to redefine the method in this category for each subclassed instance.


One option is to use class extension to hide methods.

In .h:

@interface SomeAppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@end

In .m:

@interface SomeAppDelegate()
- (void)localMethod;
@end

@implementation SomeAppDelegate

- (void)localMethod
{
}

@end

참고URL : https://stackoverflow.com/questions/3725857/protected-methods-in-objective-c

반응형