The Objective-C Runtime provides the class_addIvar C function:
BOOL class_addIvar(Class cls, const char *name, size_t size,
uint8_t alignment, const char *types)
What do I put for size
and alignment
?
I'm adding an instance variable of type UITextPosition *
, but no UITextPosition
object is in scope. For size
, can I just do sizeof(self)
, where self
is a subclass of UITextField
? I.e., can I assume that a UITextPosition
object is the same size as a UITextField
object?
How do I get alignment
?
The documentation on this stuff is not very informative, which does reflect that generally you shouldn't be using it. However, you can ask for the alignment:
char *texPosEncoding = @encode(UITextPosition);
NSUInteger textPosSize, textPosAlign;
NSGetSizeAndAlignment(textPosEncoding, &textPosSize, &textPosAlign);
class_addIvar(yourClass, "yourIvarName", textPosSize, textPosAlign, textPosEncoding);
So, first of all, the big question is 'why'. This only working on classes you're generating at runtime yourself, you can not add ivars to existing classes.
With that out of the way, in your case you're adding an ivar which is a pointer type, meaning they're all the same size. Its the size of the pointer, not the size of the object which matters.
From the documentation you linked then, you want size as sizeof(UITextPosition*)
and alignment as log2(sizeof(UITextPosition*))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With