Câu hỏi phỏng vấn Objective-C
Câu hỏi

What is a protocol, and how do you define your own and when is it used?

Câu trả lời

Protocols in Objective-C

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.

Defining Your Own Protocol

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.

Using Protocols

Protocols are used in various situations in Objective-C:

  1. Delegate Pattern: Protocols are commonly used in the delegate pattern, where an object delegates specific tasks or...
junior

junior

Gợi ý câu hỏi phỏng vấn

senior

What happens when you invoke a method on a nil pointer?

expert

Which is the best of GCD, NSThread or NSOperationQueue ?

senior

Why delegate is never retained?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào