교육/공부

[iOS][iPhone][ObjectC-04] 오브젝트C로 추상클래스를 구현하자! Protocol!

2017.08.07

 

 

안녕하세요 푸민입니다.

 

저번 포스팅까지 오브젝트 C의 기본적인 문법에 대해서 알아보았는데요.

이번 포스팅은 Protocol입니다.

 

위키 원본

Protocols[edit]

In other programming languages, these are called "interfaces".

Objective-C was extended at NeXT to introduce the concept of multiple inheritance of specification, but not implementation, through the introduction of protocols. This is a pattern achievable either as an abstract multiple inherited base class in C++, or as an "interface" (as in Java and C#). Objective-C makes use of ad hoc protocols calledinformal protocols and compiler-enforced protocols called formal protocols.

An informal protocol is a list of methods that a class can opt to implement. It is specified in the documentation, since it has no presence in the language. Informal protocols are implemented as a category (see below) on NSObject and often include optional methods, which, if implemented, can change the behavior of a class. For example, a text field class might have a delegate that implements an informal protocol with an optional method for performing auto-completion of user-typed text. The text field discovers whether the delegate implements that method (via reflection) and, if so, calls the delegate's method to support the auto-complete feature.

A formal protocol is similar to an interface in Java, C#, and Ada 2005. It is a list of methods that any class can declare itself to implement. Versions of Objective-C before 2.0 required that a class must implement all methods in a protocol it declares itself as adopting; the compiler will emit an error if the class does not implement every method from its declared protocols. Objective-C 2.0 added support for marking certain methods in a protocol optional, and the compiler will not enforce implementation of optional methods.

A class must be declared to implement that protocol to be said to conform to it. This is detectable at runtime. Formal protocols cannot provide any implementations; they simply assure callers that classes that conform to the protocol will provide implementations. In the NeXT/Apple library, protocols are frequently used by the Distributed Objects system to represent the capabilities of an object executing on a remote system.

 

자 그러면 한번 볼까요?

 

오브젝트 C에서 말하는 Protocol 은 우리가 흔히 알고 있는 Interface 와 같은 개념입니다.

즉 여러가지 추상 클래스를 기본 클래스에 적용하여 구현할 수 있는개념입니다!

객체 지향 언어의 특징이죠!

왜 저렇게 길게 설명하는지 모르겠삼... ㅋㅋㅋㅋ

 

그러면 실제 문법을 알아볼까요?

@protocol NSLocking
- (void)lock;
- (void)unlock;
@end

먼저 이렇게 Protocol 을 정의합니다.

Protocol 의 이름은 NSLocking 이 되구요.

NSLocking 프로토콜이 가지고 있는 추상메소드는 lock 과 unlock 이 있습니다!

 

간단하지요???

 

그다음에 적용을 하는 방법은

@interface NSLock : NSObject <NSLocking>
//...
@end

요렇게 NSObject(superclass 이름) 옆에 <>괄호는 이용하여 추가해줍니다!

물론 한가지만 추가되는 것이 아니라 여러가지를 추가해도 되요!

그렇게 추가한 뒤에는 내부에 추상 메소드를 구현할 수 있습니다!

 

이번 포스팅에서는 추상 클래스 Protocol을 알아보았습니다!!

모두들 즐코딩되세요~

좋아요
태그
인기 포스팅 보기