What are the Dangers of Method Swizzling in Object

2019-01-03 03:39发布

I have heard people state that method swizzling is a dangerous practice. Even the name swizzling sugests that it is a bit of a cheat.

Method Swizzling is modifying the mapping so that calling selector A will actually invoke implementation B. One use of this is to extend behavior of closed source classes.

Can we formalise the risks so that anyone who is deciding whether to use swizzling can make an informed decision whether it is worth it for what they are trying to do.

E.g.

  • Naming Collisions: If the class later extends its functionality to include the method name that you have added, it will cause a huge manner of problems. Reduce the risk by sensibly naming swizzled methods.

8条回答
我只想做你的唯一
2楼-- · 2019-01-03 04:30

Although I have used this technique, I would like to point out that:

  • It obfuscates your code because it can cause un-documented, though desired, side effects. When one reads the code he/she may be unaware of the side effect behavior that is required unless he/she remembers to search the code base to see if it has been swizzled. I'm not sure how to alleviate this problem because it is not always possible to document every place where the code is dependent upon the side effect swizzled behavior.
  • It can make your code less reusable because someone who finds a segment of code which depends upon the swizzled behavior that they would like to use elsewhere cannot simply cut and paste it into some other code base without also finding and copying the swizzled method.
查看更多
放荡不羁爱自由
3楼-- · 2019-01-03 04:30

You may end up with odd looking code like

- (void)addSubview:(UIView *)view atIndex:(NSInteger)index {
    //this looks like an infinite loop but we're swizzling so default will get called
    [self addSubview:view atIndex:index];

from actual production code related to some UI magic.

查看更多
登录 后发表回答