开发者

Method Swizzling - How to assure methods are swizzled before they are called

I'm method swizzling a third party applications creation of NSMenuItems with SIMBL, but 50/50 of the time the menu-items are created before my method swizzling is initialized.

What is a clean way to make sure my swizzling always comes first? I guess I could swizzle applicationDidFinishLaunching: and continue my swizzling there. But I'm afraid I'm going to run in to the same error there, where applicationDidFinishLaunching will be called be开发者_运维知识库fore my actual swizzle is in place.

John


You'd want the swizzle to happen as soon as the libraries are loaded. You can do that via +initialize, +load, or a constructor function.

@bbum's answer to this question has a bit more information, along with one of his blog posts on the caveats of using these special class methods.

(And I'm purposely not questioning the wisdom of what you're doing ;) )


You can use constructor functions like this:

__attribute__((constructor)) static void do_the_swizzles()
{
    // Do all your swizzling here.
}

From GCC documentation:

The constructor attribute causes the function to be called automatically before execution enters main().

Note: Although this is originally from GCC, it also works in LLVM.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜