프로토콜과 카테고리
통신 계약을 정의하는 프로토콜과 상속 없이 기존 클래스에 메서드를 추가하는 카테고리를 살펴봅니다.
프로토콜과 카테고리은(는) CoddyKit의 무료 Objective-C iOS Development for Legacy & Enterprise Apps 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Objective-C iOS Development for Legacy & Enterprise Apps 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Objective-C iOS Development for Legacy & Enterprise Apps 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Extending Behavior: Intro
Welcome to this lesson on Objective-C Protocols and Categories! These are powerful features that allow you to extend the functionality of your classes in flexible ways.
We'll explore how protocols define contracts for communication between objects and how categories let you add methods to existing classes without needing to subclass them.
Protocols: The Communication Contract
Think of an Objective-C protocol as a blueprint or a contract. It declares a list of methods that other classes can choose to implement.
- A class that 'adopts' a protocol promises to implement its required methods.
- This is crucial for establishing communication patterns, like the popular delegate pattern.
- Protocols are similar to interfaces in languages like Java or C#.
Defining a Protocol
To define a protocol, you use the @protocol directive. You can specify methods as @required (must be implemented) or @optional (can be implemented).
Protocols often conform to <NSObject>, meaning any class adopting it must be an Objective-C object.
@protocol MyServiceDelegate <NSObject>
@required
- (void)serviceDidFinishLoadingData:(NSArray *)data;
@optional
- (void)serviceDidStartRequest;
@endAdopting & Implementing a Protocol
A class adopts a protocol by listing it in angle brackets after its superclass. Then, it must implement all @required methods.
Let's see an example where a DataLoader class needs a delegate to tell it when data is ready.
#import <Foundation/Foundation.h>
// 1. Define the delegate protocol
@protocol DataLoaderDelegate <NSObject>
- (void)dataLoader:(id)loader didFinishLoadingData:(NSString *)data;
- (void)dataLoaderDidFail:(id)loader withError:(NSError *)error;
@end
// 2. Class that uses the delegate
@interface MyDataLoader : NSObject
@property (nonatomic, weak) id<DataLoaderDelegate> delegate; // The delegate property
- (void)loadData;
@end
@implementation MyDataLoader
- (void)loadData {
NSLog(@"DataLoader: Starting data load...");
// Simulate network request
NSString *result = @"Sample Data Loaded!";
// Notify the delegate
if ([self.delegate respondsToSelector:@selector(dataLoader:didFinishLoadingData:)]) {
[self.delegate dataLoader:self didFinishLoadingData:result];
}
}
@end
// 3. Class that conforms to the protocol (the delegate)
@interface MyDataConsumer : NSObject <DataLoaderDelegate> // Adopting the protocol
- (void)startConsumption;
@end
@implementation MyDataConsumer
- (void)startConsumption {
MyDataLoader *loader = [[MyDataLoader alloc] init];
loader.delegate = self; // Set self as the delegate
[loader loadData];
}
#pragma mark - DataLoaderDelegate Methods
- (void)dataLoader:(id)loader didFinishLoadingData:(NSString *)data {
NSLog(@"DataConsumer: Received data: %@", data);
}
- (void)dataLoaderDidFail:(id)loader withError:(NSError *)error {
NSLog(@"DataConsumer: Failed with error: %@", error.localizedDescription);
}
@end
// 4. Main execution
int main(int argc, const char * argv[]) {
@autoreleasepool {
MyDataConsumer *consumer = [[MyDataConsumer alloc] init];
[consumer startConsumption];
}
return 0;
}Categories: Extending Classes
Categories provide a way to add new methods to an existing class, even one you don't own (like NSString or NSObject), without modifying its original source code or creating a subclass.
- They are great for organizing code into logical groups.
- You cannot add new instance variables to a class using a category.
- If a category method has the same name as an existing method, the category's implementation will be used (this can lead to unexpected behavior!).
Defining a Category
To define a category, you create an interface file (.h) and an implementation file (.m). The syntax looks like this:
@interface ClassName (CategoryName)Let's create a category on NSString to add some utility methods.
// NSString+MyStringAdditions.h
#import <Foundation/Foundation.h>
@interface NSString (MyStringAdditions)
- (BOOL)isEmailValid;
- (NSString *)stringByCapitalizingFirstLetter;
@endImplementing Category Methods
Now let's implement the methods we declared in our NSString+MyStringAdditions category. Once implemented, these methods become available on any NSString instance!
Try running this example to see how it works:
#import <Foundation/Foundation.h>
// 1. Define the Category Interface
@interface NSString (MyStringAdditions)
- (NSString *)stringWithPrependedHello;
- (NSString *)stringWithAppendedExclamation;
@end
// 2. Implement the Category Methods
@implementation NSString (MyStringAdditions)
- (NSString *)stringWithPrependedHello {
return [NSString stringWithFormat:@"Hello, %@", self];
}
- (NSString *)stringWithAppendedExclamation {
return [NSString stringWithFormat:@"%@!", self];
}
@end
// 3. Main execution
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSString *name = @"CoddyKit";
// Use category methods
NSString *greeting = [name stringWithPrependedHello];
NSString *excitedGreeting = [greeting stringWithAppendedExclamation];
NSLog(@"Original: %@", name);
NSLog(@"Greeting: %@", greeting);
NSLog(@"Excited: %@", excitedGreeting);
}
return 0;
}When to Use Protocols vs. Categories
It's important to know when to choose between protocols and categories:
- Protocols: Use when you need to define a common interface or contract that multiple unrelated classes might conform to (e.g., delegate pattern, data sources). They define what an object can do.
- Categories: Use when you want to add utility methods to an existing class, group related methods, or extend a class without subclassing (e.g., adding a custom parsing method to
NSString). They extend how an object can behave.
Protocols & Inheritance
A protocol can also adopt other protocols, creating a hierarchy of requirements. For example, @protocol ChildProtocol <ParentProtocol> means ChildProtocol includes all methods from ParentProtocol.
This allows you to build more complex contracts by combining simpler ones.
Quick Check: Protocols
Consider the following Objective-C code snippet:
@protocol DataProcessor
@required
- (void)processData:(NSArray *)data;
@optional
- (void)didStartProcessing;
@end What is the primary purpose of this protocol?
Recap: Protocols & Categories
Great job! In this lesson, you learned about two powerful Objective-C features:
- Protocols: Define a contract of methods that classes can adopt to enable communication and establish common interfaces.
- Categories: Extend existing classes by adding new methods without inheritance, useful for utility functions and code organization.
Mastering these will help you build more flexible and modular Objective-C applications!
자주 묻는 질문
“프로토콜과 카테고리” 강의는 무료인가요?
네 — “프로토콜과 카테고리” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Objective-C iOS Development for Legacy & Enterprise Apps 강의 전체를 잠금 해제할 수 있습니다. Objective-C iOS Development for Legacy & Enterprise Apps 강의에는 총 4개의 강의가 포함되어 있습니다.
“프로토콜과 카테고리”에서 뭘 배우나요?
통신 계약을 정의하는 프로토콜과 상속 없이 기존 클래스에 메서드를 추가하는 카테고리를 살펴봅니다. 브라우저에서 직접 실행하는 실습 코드로 Objective-C iOS Development for Legacy & Enterprise Apps을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Objective-C iOS Development for Legacy & Enterprise Apps을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Objective-C iOS Development for Legacy & Enterprise Apps은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“프로토콜과 카테고리” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Objective-C iOS Development for Legacy & Enterprise Apps 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Objective-C iOS Development for Legacy & Enterprise Apps 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 클래스, 객체 및 메서드
- 속성과 인스턴스 변수
- 프로토콜과 카테고리
- 상속과 메서드 재정의