开发者

Are empty Obj-C methods being removed during compilation?

Let's assume that I have a method in class like this:

- (void)doSomethingOnlyWhenNeeded {
开发者_开发百科    #ifdef NEEDED

    DO SOMETHING

    #endif
}

If I define NEEDED, everything is OK. But if NEEDED is not defined than method is empty and I want it to be removed. Is there any optimization that removes calls to such empty methods? If not, why that can be a bad idea? If yes, then do I have any control over that?

Where to find documentation on this feature?


They are not removed during compilation, this can be a way to override a super class method, and it will stop that method being called regardless of the contents of the child classes method, this is how I am assuming the method persists with no content.


Why not use your #ifdef NEEDED also when potentially calling the function?

Alternatively, you can use blocks. First you can declare the block:

void (^someBlock)(void);

And then create it if needed

#ifdef NEEDED

someBlock = ^{
  //do something
};

#endif

When calling it, you can do this:

if (someBlock)
  someBlock();

This will not call the block if it doesn't exist.


No, I don't believe those will be optimized out. Now, this is not a huge concern except if called ridiculously frequently. If you're in an incredibly tight loop, then you should put the conditional around the message send rather than inside of the method.

But basically, if you haven't noticed your app running slowly and been pointed to that method by Instruments, then just do what you're doing and move on to more important coding concerns. :)


Perhaps I'm missing something, but why don't you wrap the method itself in the preprocessor block, e.g.

#ifdef NEEDED
- (void)doSomethingOnlyWhenNeeded {
    DO SOMETHING
}
#endif

There, the method is now no longer there. :-)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜