iOS under 13 to access restricted _ivar

First appeared in public No.

Before iOS 13, generally use KVC to achieve access to the private instance variable, such as access to the UITextField _placeholderLabel usually do:

extension UITextField {
    var placeholderLabel: UILabel? {
        get {
            return value(forKey: "_placeholderLabel") as? UILabel
        }
    }
}
复制代码

Up to 12, this method is well run iOS, but upgraded to iOS 13, when running on crashes:

*** Terminating app due to uncaught exception 'NSGenericException', reason: 'Access to UITextField's _placeholderLabel ivar is prohibited. This is an application bug'

Meaning is clear, that prohibit access ivar, and this is caused by the bug APP.

Well, KVC not be used, it is necessary to adapt iOS 13, while keeping the original logic, how to do it? There runtime can try!

extension UITextField {
    var placeholderLabel: UILabel? {
        get {
            return getIvar(name: "_placeholderLabel") as? UILabel
        }
    }
}
复制代码

Re-run, APP no longer collapsed.

getIvar method is an extension of my package, use the runtime to access _ivar, the code is relatively simple:

extension NSObject {
    func getIvar(name: String) -> Any? {
        guard let _var = class_getInstanceVariable(type(of: self), name) else {
            return nil
        }

        return object_getIvar(self, _var)
    }
}
复制代码

From these details change can probably understand the attitude of Apple developers, officials hope the developers try not to use clever but useless, neatly developed in accordance with the document on the line.

However, demand does not allow ah ...

Currently only for iOS 13 still in developer testing version, there may be as many after developers need to step on the pit.

Reproduced in: https: //juejin.im/post/5cfc5e975188256073337c6a

Guess you like

Origin blog.csdn.net/weixin_34162629/article/details/91480108