What is a protocol, and how do you define your own and when is it used?
What is a protocol, and how do you define your own and when is it used?
In Objective-C, a protocol is a blueprint that defines a set of methods and properties that a class can adopt. It specifies the interface that a class must implement, but it does not provide any implementation details. Protocols are used to define a contract between different parts of an application, allowing for better code organization, reusability, and interoperability.
To define your own protocol in Objective-C, you use the @protocol
keyword followed by the name of the protocol. Inside the protocol definition, you declare the methods and properties that adopting classes must implement. For example:
@protocol MyProtocol
- (void)doSomething;
@property (nonatomic, copy) NSString *myProperty;
@end
In this example, we define a protocol named MyProtocol
that requires adopting classes to implement a method named doSomething
and a property named myProperty
.
Protocols are used in various situations in Objective-C:
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào