scoped_block_swizzler.h 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // Copyright 2013 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. //
  5. #ifndef IOS_TESTING_SCOPED_BLOCK_SWIZZLER_H_
  6. #define IOS_TESTING_SCOPED_BLOCK_SWIZZLER_H_
  7. #include <objc/runtime.h>
  8. // Helper class that replaces a method implementation with a given block.
  9. // ScopedBlockSwizzler automatically swizzles when it is constructed and
  10. // reinstalls the original method implementation when it goes out of scope.
  11. class ScopedBlockSwizzler {
  12. public:
  13. // Constructs a new ScopedBlockSwizzler object and replaces the implementation
  14. // of |selector| on the |target| class with the given |block|.
  15. // ScopedBlockSwizzler first tries to swizzle a class method; if one is not
  16. // found, it tries to swizzle an instance method. It is an error to pass a
  17. // |selector| that does not exist on the |target| class.
  18. ScopedBlockSwizzler(Class target, SEL selector, id block);
  19. // Constructs a new ScopedBlockSwizzler object and replaces the implementation
  20. // of |selector| on the |target| class with the given |block|.
  21. // |class_method| specifies if the swizzled method is a class method (YES) or
  22. // an instance method (NO). This can be use to disambiguate if the class
  23. // contains both method types with the same selector.
  24. ScopedBlockSwizzler(Class target, SEL selector, id block, BOOL class_method);
  25. ScopedBlockSwizzler(const ScopedBlockSwizzler&) = delete;
  26. ScopedBlockSwizzler& operator=(const ScopedBlockSwizzler&) = delete;
  27. // Destroys the ScopedBlockSwizzler object, removing the swizzled method and
  28. // reinstalling the original method implementation.
  29. virtual ~ScopedBlockSwizzler();
  30. private:
  31. // The method that is to be swizzled. Can be either a class method or an
  32. // instance method.
  33. Method method_;
  34. // The original implementation of the swizzled method, saved so that it can be
  35. // reinstalled when this object goes out of scope.
  36. IMP original_imp_;
  37. };
  38. #endif // IOS_TESTING_SCOPED_BLOCK_SWIZZLER_H_