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

余生长醉 提交于 2019-12-03 16:44:35

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

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