Câu hỏi phỏng vấn Swift
Câu hỏi

When to use @objc attribute?

Câu trả lời

The @objc attribute in Swift is used to expose Swift code to the Objective-C runtime, making it accessible from Objective-C. This is particularly important for interoperability between Swift and Objective-C, which is common in iOS development due to the extensive use of Objective-C in many existing frameworks and libraries.

Here are the key scenarios when you should use the @objc attribute:

  1. Interacting with Objective-C APIs: If you need to call Swift methods from Objective-C code, you must mark those methods with @objc. This is essential when working with APIs that are written in Objective-C, such as many parts of UIKit and other Apple frameworks[1][2][5].

    swift Copy
    @objc func greet() {
        print("Hello, world!")
    }
  2. Using Objective-C Features: Some features, like selectors, Key-Value Observing (KVO), and Key-Value Coding (KVC), are specific to Objective-C. To use these features with Swift methods, you need to mark them with @objc[2][3].

    swift Copy
    @objc private func doubleTapGestureRecognized(recognizer: UITapGestureRecognizer) {
        // Handle double tap
    }
  3. Dynamic Dispatch: If you need dynamic dispatch, which is a feature of the Objective-C runtime, you should use @objc dynamic. This is often used in conjunction with KVO or when you need to override methods dynamically at runtime[3].

    swift Copy
    @objc dynamic func performOperation() -> Int {
        return 42
    }
  4. Customizing Objective-C Names: You can use @objc to provide custom names for Swift methods or properties when they are exposed to Objective-C. This can help maintain consistency with Objective-C naming conventions[4].

    swift Copy
    @objc(sharedManager)
    static let shared = MyManager()
  5. Exposing Entire Classes: If you want to expose all members of a class to Objective-C, you can use the @objcMembers attribute on the class. This automatically applies @objc to all members of the class, its extensions, and its subclasses[1][6].

    swift Copy
    @objcMembers class Gr...
middle

middle

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

middle

How to sort array of custom objects by property value in Swift?

senior

What is Copy on Write (Cow) in Swift?

senior

Explain when to use different Swift casting operators?

Bình luận

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

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