Skip to content

Instantly share code, notes, and snippets.

@steipete
Created October 26, 2012 16:32
Show Gist options
  • Save steipete/3959770 to your computer and use it in GitHub Desktop.
Save steipete/3959770 to your computer and use it in GitHub Desktop.
Macro Helpers for atomic read/write of properties.
// Atomic getting/setting of properties.
// See http://www.opensource.apple.com/source/objc4/objc4-371.2/runtime/Accessors.subproj/objc-accessors.h
extern void objc_setProperty(id self, SEL _cmd, ptrdiff_t offset, id newValue, BOOL atomic, BOOL shouldCopy);
extern id objc_getProperty(id self, SEL _cmd, ptrdiff_t offset, BOOL atomic);
extern void objc_copyStruct(void *dest, const void *src, ptrdiff_t size, BOOL atomic, BOOL hasStrong);
#define PSPDFAtomicRetainedSetToFrom(dest, source) objc_setProperty(self, _cmd, (ptrdiff_t)(&dest) - (ptrdiff_t)(self), source, YES, NO)
#define PSPDFAtomicCopiedSetToFrom(dest, source) objc_setProperty(self, _cmd, (ptrdiff_t)(&dest) - (ptrdiff_t)(self), source, YES, YES)
#define PSPDFAtomicAutoreleasedGet(source) objc_getProperty(self, _cmd, (ptrdiff_t)(&source) - (ptrdiff_t)(self), YES)
#define PSPDFAtomicStructToFrom(dest, source) objc_copyStruct(&dest, &source, sizeof(__typeof__(source)), YES, NO)
@steipete
Copy link
Author

This is super useful when you want atomic properties but also want to override them. It's the same that Apple internally uses when set to atomic.

Weird thing is just that I can't find the objc_setProperty declarations in a public header. Is this a good idea to use?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment