setAssociatedObjectHook.m 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // TEST_CONFIG
  2. #include "test.h"
  3. #include "testroot.i"
  4. id sawObject;
  5. const void *sawKey;
  6. id sawValue;
  7. objc_AssociationPolicy sawPolicy;
  8. objc_hook_setAssociatedObject originalSetAssociatedObject;
  9. void hook(id _Nonnull object, const void * _Nonnull key, id _Nullable value, objc_AssociationPolicy policy) {
  10. sawObject = object;
  11. sawKey = key;
  12. sawValue = value;
  13. sawPolicy = policy;
  14. originalSetAssociatedObject(object, key, value, policy);
  15. }
  16. int main() {
  17. id obj = [TestRoot new];
  18. id value = [TestRoot new];
  19. const void *key = "key";
  20. objc_setAssociatedObject(obj, key, value, OBJC_ASSOCIATION_RETAIN);
  21. testassert(sawObject == nil);
  22. testassert(sawKey == nil);
  23. testassert(sawValue == nil);
  24. testassert(sawPolicy == 0);
  25. id out = objc_getAssociatedObject(obj, key);
  26. testassert(out == value);
  27. objc_setHook_setAssociatedObject(hook, &originalSetAssociatedObject);
  28. key = "key2";
  29. objc_setAssociatedObject(obj, key, value, OBJC_ASSOCIATION_RETAIN);
  30. testassert(sawObject == obj);
  31. testassert(sawKey == key);
  32. testassert(sawValue == value);
  33. testassert(sawPolicy == OBJC_ASSOCIATION_RETAIN);
  34. out = objc_getAssociatedObject(obj, key);
  35. testassert(out == value);
  36. succeed(__FILE__);
  37. }