问题
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