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].

    @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].

    @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].

    @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].

    @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].

    @objcMembers class Gr...
middle

middle

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

middle

What is the difference between let and var in Swift?

senior

What is the difference between static func and class func in Swift?

senior

Is there a way to create an abstract class in Swift?

Bình luận

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

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