Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C Runtime: What to put for size & alignment for class_addIvar?

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?

like image 343
ma11hew28 Avatar asked Dec 21 '22 07:12

ma11hew28


2 Answers

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);
like image 134
Seamus Campbell Avatar answered Jan 25 '23 11:01

Seamus Campbell


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*))

like image 22
Joshua Weinberg Avatar answered Jan 25 '23 10:01

Joshua Weinberg