Method swizzling in Swift

后端 未结 5 1649
深忆病人
深忆病人 2020-12-24 09:38

There is a little problem with UINavigationBar which I\'m trying to overcome. When you hide the status bar using prefersStatusBarHidden() method in

5条回答
  •  粉色の甜心
    2020-12-24 10:06

    Swift doesn't implement the load() class method on extensions. Unlike ObjC, where the runtime calls +load for each class and category, in Swift the runtime only calls the load() class method defined on a class; Swift 1.1 ignores load() class methods defined in extensions. In ObjC, it is acceptable for each category to override +load so that each class/category can register for notifications or perform some other initialization (like swizzling) when that category/class loads.

    Like ObjC, you should not override the initialize() class method in your extensions to perform swizzling. If you were to implement the initialize() class method in multiple extensions, only one implementation would be called. This is different than the +load method where the runtime calls all implementations when the app launches.

    So, to initialize the state of an extension, you can either call the method from the app delegate when the app finishes launching, or from an ObjC stub when the runtime calls the +load methods. Since each extension could have a load method, they should be uniquely named. Assuming that you have SomeClass which is descended from NSObject, the code for the ObjC stub would look something like this:

    In your SomeClass+Foo.swift file:

    extension SomeClass {
        class func loadFoo {
            ...do your class initialization here...
        }
    }
    

    In your SomeClass+Foo.m file:

    @implementation SomeClass(Foo)
        + (void)load {
            [self performSelector:@selector(loadFoo);
        }
    @end
    

提交回复
热议问题