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

久未见 提交于 2019-12-09 13:20:47

问题


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?


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/7942345/objective-c-runtime-what-to-put-for-size-alignment-for-class-addivar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!