Nice programing

Objective-C에서 프로토콜 / 델리게이트를 확장하는 방법

nicepro 2020. 10. 26. 21:07
반응형

Objective-C에서 프로토콜 / 델리게이트를 확장하는 방법


AVAudioPlayer와 같은 클래스를 확장하려면 AVAudioPlayerDelegate에 다른 메서드를 추가하는 가장 좋은 방법은 무엇입니까? 카테고리를 만들고 확장합니까? 확장하면 실제 대리자 getter / setter를 덮어 써야합니까? 프로토콜을 어떻게 확장합니까? 다음은 오류를 제공합니다.



@protocol AudioTrackDelegate : AVAudioPlayerDelegate {
    - (void)foo;
}
@end

@interface AudioTrack : AVAudioPlayer {
}
@end

다른 프로토콜을 구현하는 프로토콜을 만드는 구문은 다음과 같습니다.

@protocol NewProtocol <OldProtocol>
- (void)foo;
@end

당신의 메소드를 호출 할 경우 NewProtocol로 입력 포인터에 OldProtocol당신이 중 하나를 호출 할 수 있습니다 respondsToSelector:

if ([object respondsToSelector:@selector(foo)])
    [(id)object foo];

또는 스터브 메서드를에 대한 범주로 정의하십시오 NSObject.

@interface NSObject (NewProtocol)
- (void)foo;
@end
@implementation NSObject (NewProtocol)
- (void)foo
{
}
@end

프로토콜은 컴파일 된 앱에 코드를 추가하지 않습니다. 클래스가 프로토콜을 "준수"하는 것으로 간주되는 메서드를 구현해야한다는 사실 만 적용합니다. 이것의 좋은 사용은 모든 동일한 작동 방식으로 클래스 그룹을 생성하는 것입니다 : <printable>또는 <serialized>등. 따라서 <plays>예를 들어 프로토콜을 만들 수 있습니다 .

@protocol plays
    - (void) play;
    - (NSString *) type;
@end

그리고 준수하는 클래스는 <plays>반드시 playtype메소드를 구현해야 합니다. 그렇지 않은 경우 컴파일러는 경고를 발행하지만 어쨌든 클래스를 컴파일합니다. 코드에서 객체가 다음 코드를 사용하여 프로토콜을 준수하는지 확인합니다.

if ([obj conformsTo: @protocol(plays)]) {
    [obj play];
}

범주는 실제로 클래스에 동적으로 새 메서드를 추가합니다. 이러한 메서드는 선택기로 런타임에 전역 적으로 액세스 할 수 있으며에서 @selector(foo)같이 이름으로 호출 할 수 있습니다.[object foo:bar];

카테고리의 목적은 해당 클래스에 대한 소스 코드가 없더라도 클래스에 특별한 새 코드를 추가하는 것입니다. 보안 문제가있을 수 있으며 클래스 등에서 메모리 누수가 발생할 수 있습니다.

귀하의 경우에는 아마도 별도의 파일에 AVAudioPlayerDelegate_TrackOps.m

#import "AVAudioPlayerDelegate.h"
@implementation AVAudioPlayerDelegate (TrackOps)

- (NSObject *) foo {
    // do foo stuff;
    return bar;
}

@end

카테고리로 지정 NSObject하면 모든 클래스가에 응답합니다 foo. Foo독립형 방법 Objc_perform_selector(@selector(foo))일 수도 있습니다.

Bottom Line: use a category to add a quick method to a class, protocols for enforcing method implementations, and subclasses to specialize existing classes (things like adding member variables or major new functionality). Categories can also be used to override a method or two when a subclass is not needed and wanted, but usually if you want to add functionality to a class you make a subclass. For more examples, ideas, other general information on this topic, there's always the Apple introduction to Objective-C

참고URL : https://stackoverflow.com/questions/732701/how-to-extend-protocols-delegates-in-objective-c

반응형